从数字数组中获取一个数字 [英] Get a number from an array of digits
本文介绍了从数字数组中获取一个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
要将数字拆分为给定基数的数字,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
什么是反向操作?如果您有一个数字数组和底数,是否有一种 内置 方法可以将其转换为数字?我可以将数组打印为字符串并使用 parse()
,但这听起来效率低下,也不适用于基数 > 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
这篇关于从数字数组中获取一个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文