对于数字 n,我只能想到
有没有更优雅的方法?
array_of_digits = n.to_s.split('').map(&:to_i)
有没有更优雅的方法?
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)
n.to_s.chars.map(&:to_i)
进行比较吗? - Neil SlaterFixnum#to_s
内部也有类似的东西)。无论哪种方式,都是好答案。 - Neil Slater
each_byte
方法很有趣,但我认为大多数Ruby程序员会选择你所拥有的,尽管我认为string_of_digits = n.to_s.each_char.map(&:to_i)
是一个小改进,因为它不会创建中间数组。 - Cary Swoveland