从数字数组中获取数字

编程入门 行业动态 更新时间:2024-10-09 16:23:04
本文介绍了从数字数组中获取数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

要在给定的基数中将数字拆分为数字,Julia可以使用 digits() 函数:

To split a number into digits in a given base, Julia has the digits() function:

julia> digits(36, base = 4) 3-element Array{Int64,1}: 0 1 2

什么是反向操作?如果您有一个由数字和基数组成的数组,是否有内置方式将其转换为数字?我可以将数组打印为字符串,然后使用 ,但这听起来效率低下,并且对于大于10的基数也不起作用.

What's the reverse operation? If you have an array of digits and the base, is there a built-in way to convert that to a number? I could print the array to a string and use parse(), but that sounds inefficient, and also wouldn't work for bases > 10.

推荐答案

答案似乎直接写在digits的文档中:

The answer seems to be written directly within the documentation of digits:

help?> digits search: digits digits! ndigits isdigit isxdigit disable_sigint digits([T<:Integer], n::Integer; base::T = 10, pad::Integer = 1) Return an array with element type T (default Int) of the digits of n in the given base, optionally padded with zeros to a specified size. More significant digits are at higher indices, such that n == sum([digits[k]*base^(k-1) for k=1:length(digits)]).

对于您的情况,这将起作用:

So for your case this will work:

julia> d = digits(36, base = 4); julia> sum([d[k]*4^(k-1) for k=1:length(d)]) 36

上面的代码可以使用点运算符来缩短:

And the above code can be shortened with the dot operator:

julia> sum(d.*4 .^(0:(length(d)-1))) 36

更多推荐

从数字数组中获取数字

本文发布于:2023-11-30 18:22:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651049.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中   字数   数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!