额...请问怎么用 ruby 实现 1000!的末尾有多少个连续的 0
(1..1000).each do |i|
s = s * i
end
c = 0
loop do
f = s % 10
c += 1 if f == 0
s = s / 10
break if f != 0
end
puts c #=> 249
法二
l = s.to_s.size
s = s.to_s
c = 0
loop do
c += 1 if s[l] == '0'
l -= 1
break if s[l] != '0'
end
puts c #=> 249
貌似是 249
num = (1..1000).reduce(&:*).to_s
num.size - num.reverse.to_i.to_s.size
# 或
num[/[0]*$/].size
def count_zeros(n)
zeros = 0
five = 5
while five < n
zeros += n / five
five *= 5
end
zeros
end
count_zeros(1000)
#=> 249
去做 1000 次乘法的我也是醉了。
常见面试题: https://leetcode.com/problems/factorial-trailing-zeroes/
n = 1000
[1,2,3,4].map{|i| n / 5 ** i}.inject(:+)
def trailing_zeroes(n) # 尾随零
num = n / 5
num == 0 ? 0 : num + trailing_zeroes(num)
end
抛砖引玉
a = (1..1000).inject(0) do |sum, num|
while(num%5==0)
sum += 1
num /= 5
end
sum
end
puts a