4

For number n, I could only think of

array_of_digits = n.to_s.split('').map(&:to_i)

Is there any more elegant method?

4

1 回答 1

6

不是更优雅,而是更快:

def digits(n)
  (0..Math.log10(n).to_i).map { |dp| n / 10 ** dp % 10 }.reverse
end

我刚刚找到的另一个快速(最快)

def digits(n)
  n.to_s.each_byte.map { |x| x - 48 }
end

基准:

            user     system      total        real
Split map  0.410000   0.000000   0.410000 (  0.412397)
chars      0.100000   0.010000   0.110000 (  0.104450)
each byte  0.070000   0.000000   0.070000 (  0.068171)
Numerical  0.100000   0.000000   0.100000 (  0.101828)

顺便说一下,基准测试的代码在这里:https ://gist.github.com/sid-code/9ad26dc4b509bfb86810

于 2015-04-12T17:56:36.207 回答