在我正在编写的脚本中,我希望找到Ruby中Fixnum的长度。我可以做<num>.to_s.length,但是有没有办法直接找到Fixnum的长度而不把它转换成字符串呢?
发布于 2012-12-23 03:04:40
puts Math.log10(1234).to_i + 1 # => 4您可以将其添加到Fixnum,如下所示:
class Fixnum
def num_digits
Math.log10(self).to_i + 1
end
end
puts 1234.num_digits # => 4发布于 2016-12-27 01:22:12
Ruby2.4有一个Integer#digits方法,它返回一个包含数字的数组。
num = 123456
num.digits
# => [6, 5, 4, 3, 2, 1]
num.digits.count
# => 6 编辑:
要处理负数(感谢@MatzFan),请使用绝对值。Integer#abs
-123456.abs.digits
# => [6, 5, 4, 3, 2, 1]发布于 2018-02-19 21:04:17
Ruby 2.4+的侧记
我在不同的解决方案上运行了一些基准测试,Math.log10(x).to_i + 1实际上比x.to_s.length快得多。comment from @Wayne Conrad已过期。new solution with digits.count远远落在后面,尤其是数字更大的:
with_10_digits = 2_040_240_420
print Benchmark.measure { 1_000_000.times { Math.log10(with_10_digits).to_i + 1 } }
# => 0.100000 0.000000 0.100000 ( 0.109846)
print Benchmark.measure { 1_000_000.times { with_10_digits.to_s.length } }
# => 0.360000 0.000000 0.360000 ( 0.362604)
print Benchmark.measure { 1_000_000.times { with_10_digits.digits.count } }
# => 0.690000 0.020000 0.710000 ( 0.717554)
with_42_digits = 750_325_442_042_020_572_057_420_745_037_450_237_570_322
print Benchmark.measure { 1_000_000.times { Math.log10(with_42_digits).to_i + 1 } }
# => 0.140000 0.000000 0.140000 ( 0.142757)
print Benchmark.measure { 1_000_000.times { with_42_digits.to_s.length } }
# => 1.180000 0.000000 1.180000 ( 1.186603)
print Benchmark.measure { 1_000_000.times { with_42_digits.digits.count } }
# => 8.480000 0.040000 8.520000 ( 8.577174)https://stackoverflow.com/questions/14005524
复制相似问题