LintCode 2. Trailing Zeros
Write an algorithm which computes the number of trailing zeros in n factorial.
题意分析
n!末尾含零的个数,这个题关键在于n!有多少5,2*5=10,每凑成一对就多一个0,2的个数远比5多,所以关键是找5.
可以列出几个例子来观察一下:
1 * 2 * 3 * 4 * (5) * 6 * 7 * 8 * 9 * (10) * 11 * 12 * 13 * 14 * (15) * 16 * 17 * 18 * 19 * (20) * 21 * 22 * 23 * 24 * ((25)) * 26 * 27 * 28 * 29 * (30)
- 每5个数有一个5结尾的,那么 n/5 便是5结尾数的个数,如 31/5 = 6,分别对应【5, 10, 15,20, 25, 30】
- 注意! 25可以分成5 * 5, 所以又多了一个5.
- 诸如25,125之类的数字有不止一个5。处理这个问题也很简单,首先对n÷5,可将上述转换为【1, 2, 3, 4,(5),6】
- 我们可以形象的看作在算括号个数,如((25)), ((50)), ((75)), ((100)), (((125))),这种5^i×j的数都会套多层括号,n每次除以5都会去一层括号,直至括号去完。
class Solution {
public:
/*
* @param n: A long integer
* @return: An integer, denote the number of trailing zeros in n!
*/
long long trailingZeros(long long n) {
// write your code here, try to do it without arithmetic operators.
long long num = 0;
while (n) {
num += n / 5;
n /= 5;
}
return num;
}
};