LintCode 2.尾部的零 C++
2018-01-27 16:22
776 查看
LintCode 2.尾部的零 C++
问题描述:设计一个算法,计算出n阶乘中尾部零的个数
样例:11! = 39916800,因此应该返回
2
分析:把1×2×3×4×……×n中每一个数因式分解,会出现:
1×2×3×(2×2)×5×(2×3)×……
像这样。十进制数结尾的有多少个0,就表示其因数里有多少个10——其他进制也一样,一个M进制的数,让结尾多一个0就等价于乘以M。对于十进制来说,有多少个10,就意味着有多少个5(10=2×5,2有很多)
9123
。那么,我们可以循环统计可以整除5、25、125......的数,即可得出零的个数。
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 count = 0;
long long fiveTimes = 1;
while(fiveTimes * 5 <= n){
fiveTimes = fiveTimes * 5;
count += n / fiveTimes;
}
return count;
}
};代码借鉴:http://blog.csdn.net/hk_john/article/details/78806907
如有错误,请批评指出。
问题描述:设计一个算法,计算出n阶乘中尾部零的个数
样例:11! = 39916800,因此应该返回
2
分析:把1×2×3×4×……×n中每一个数因式分解,会出现:
1×2×3×(2×2)×5×(2×3)×……
像这样。十进制数结尾的有多少个0,就表示其因数里有多少个10——其他进制也一样,一个M进制的数,让结尾多一个0就等价于乘以M。对于十进制来说,有多少个10,就意味着有多少个5(10=2×5,2有很多)
9123
。那么,我们可以循环统计可以整除5、25、125......的数,即可得出零的个数。
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 count = 0;
long long fiveTimes = 1;
while(fiveTimes * 5 <= n){
fiveTimes = fiveTimes * 5;
count += n / fiveTimes;
}
return count;
}
};代码借鉴:http://blog.csdn.net/hk_john/article/details/78806907
如有错误,请批评指出。
相关文章推荐
- LintCode 8.旋转字符串 C++
- Lintcode 2. 尾部的零
- LintCode 第二题 计算阶乘结果尾部的零
- LintCode 452.删除链表中的元素 C++
- C/C++面试之算法系列--N!的尾部连续0的个数
- [LintCode]Remove Linked List Elements(C++)
- 112. 删除排序链表中的重复元素(remove-duplicates-from-sorted-list)(c++)----lintcode面试题之链表
- LintCode_208 Assignment Operator Overloading (C++ Only)
- 173. 链表插入排序 (insertion-sort-list)(c++)----lintcode面试题之链表
- LintCode 2 : 尾部的零(java实现)
- lintcode-2-尾部的零
- LintCode 466.链表节点计数 C++
- 466. 链表节点计数 (count-linked-list-nodes)(c++)----lintcode面试题之链表
- 96. 链表划分(partition-list)(c++)----lintcode面试题之链表
- lintcode 2.尾部的零
- 167. 链表求和(add-two-numbers)(c++)----lintcode面试题之链表
- C/C++结构体内尾部0字节字符数组技巧
- LintCode-662. 猜数游戏(C++)
- LintCode-6合并排序数组 II(C++)
- 【计算连乘积中末尾0的个数】LintCode 尾部的零