Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
方法:求乘积中5的个数。
class Solution {
public:
int trailingZeroes(int n) {
long num5 = 0; //int overflow
long base = 5;
while(n/base){
num5 += n/base;
base *= 5;
}
return num5;
}
};
切忌不可用int类型定义,容易溢出。
防止溢出可以换种编程方式进行。
class Solution {
public:
int trailingZeroes(int n) {
long num5 = 0; //int overflow
while(n){
num5 += n/5;
n/= 5;
}
return num5;
}
};