【Leetcode】 Factorial Trailing Zeroes #172
2015-07-26 06:27
567 查看
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
求末尾0的个数,即为求各factor中5的个数,因为每有一个5必有一个2与之组成10。其中factor 5^n 应被计算n次,因为其贡献了n个5.
5的倍数有:a = n/5
则25的倍数有:b = a/5
125的倍数有:c=b/5
....
根据此思路,得:
class Solution {
public:
int trailingZeroes(int n) {
int number_of_trailing_zero = 0;
int num_of_5 = n/5;
while(num_of_5 != 0) {
number_of_trailing_zero += num_of_5;
num_of_5 /= 5;
}
return number_of_trailing_zero;
}
};
Note: Your solution should be in logarithmic time complexity.
求末尾0的个数,即为求各factor中5的个数,因为每有一个5必有一个2与之组成10。其中factor 5^n 应被计算n次,因为其贡献了n个5.
5的倍数有:a = n/5
则25的倍数有:b = a/5
125的倍数有:c=b/5
....
根据此思路,得:
class Solution {
public:
int trailingZeroes(int n) {
int number_of_trailing_zero = 0;
int num_of_5 = n/5;
while(num_of_5 != 0) {
number_of_trailing_zero += num_of_5;
num_of_5 /= 5;
}
return number_of_trailing_zero;
}
};
相关文章推荐
- rails总结
- rails总结
- Hive Failed with exception Unable to rename
- 2015 Multi-University Training Contest 2 1002
- 2009 Multi-University Training Contest 10 - Host by NIT
- 为什么wait(),notify()和notifyAll()必须在同步块或同步方法中调
- 杭电ACM HDU 2674 N!Again
- UVa1437&LA4394 StringPainter
- Scala入门到精通——第十节 Scala类层次结构、Traits初步
- Container With Most Water (头尾指针的妙用)
- synchronized , wait() , notify() and notifyAll()
- Climbing Stairs
- strcpy,strncpy http://blog.csdn.net/shutear/article/details/8256096
- int main(int argc, char*argv[])
- 2015 Multi-University Training Contest 2 hdu 5308 I Wanna Become A 24-Point Master
- ECHOSRV.C中的main()设立一个 I/O completion port
- 【bzoj4152】 AMPPZ2014The Captain 最短路
- 一刀斩 :“SVN” failed to start 服务启动失败
- UVA - 10976 Fractions Again?!
- centos中w使用smbclient连接window出现:session setup failed: NT_STATUS_LOGON_FAILURE