本文介绍了从数字数组中获取数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
要在给定的基数中将数字拆分为数字,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更多推荐
从数字数组中获取数字
发布评论