Get a number from an array of digits

后端 未结 2 728
悲哀的现实
悲哀的现实 2021-01-25 07:16

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
2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-25 08:06

    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
    

提交回复
热议问题