C++實(shí)現(xiàn)LeetCode(172.求階乘末尾零的個(gè)數(shù))
[LeetCode] 172. Factorial Trailing Zeroes 求階乘末尾零的個(gè)數(shù)
Given an integer n, return the number of trailing zeroes in n!.
Example 1:
Input: 3
Output: 0
Explanation: 3! = 6, no trailing zero.
Example 2:
Input: 5
Output: 1
Explanation: 5! = 120, one trailing zero.
Note: Your solution should be in logarithmic time complexity.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
這道題并沒(méi)有什么難度,是讓求一個(gè)數(shù)的階乘末尾0的個(gè)數(shù),也就是要找乘數(shù)中 10 的個(gè)數(shù),而 10 可分解為2和5,而2的數(shù)量又遠(yuǎn)大于5的數(shù)量(比如1到 10 中有2個(gè)5,5個(gè)2),那么此題即便為找出5的個(gè)數(shù)。仍需注意的一點(diǎn)就是,像 25,125,這樣的不只含有一個(gè)5的數(shù)字需要考慮進(jìn)去,參加代碼如下:
C++ 解法一:
class Solution {
public:
int trailingZeroes(int n) {
int res = 0;
while (n) {
res += n / 5;
n /= 5;
}
return res;
}
};
Java 解法一:
public class Solution {
public int trailingZeroes(int n) {
int res = 0;
while (n > 0) {
res += n / 5;
n /= 5;
}
return res;
}
}
這題還有遞歸的解法,思路和上面完全一樣,寫(xiě)法更簡(jiǎn)潔了,一行搞定碉堡了。
C++ 解法二:
class Solution {
public:
int trailingZeroes(int n) {
return n == 0 ? 0 : n / 5 + trailingZeroes(n / 5);
}
};
Java 解法二:
public class Solution {
public int trailingZeroes(int n) {
return n == 0 ? 0 : n / 5 + trailingZeroes(n / 5);
}
}
Github 同步地址:
https://github.com/grandyang/leetcode/issues/172
類似題目:
Preimage Size of Factorial Zeroes Function
參考資料:
https://leetcode.com/problems/factorial-trailing-zeroes/
到此這篇關(guān)于C++實(shí)現(xiàn)LeetCode(172.求階乘末尾零的個(gè)數(shù))的文章就介紹到這了,更多相關(guān)C++實(shí)現(xiàn)求階乘末尾零的個(gè)數(shù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- C++實(shí)現(xiàn)LeetCode(188.買賣股票的最佳時(shí)間之四)
- C++實(shí)現(xiàn)LeetCode(557.翻轉(zhuǎn)字符串中的單詞之三)
- C++實(shí)現(xiàn)LeetCode(186.翻轉(zhuǎn)字符串中的單詞之二)
- C++實(shí)現(xiàn)LeetCode(173.二叉搜索樹(shù)迭代器)
- C++實(shí)現(xiàn)LeetCode(170.兩數(shù)之和之三 - 數(shù)據(jù)結(jié)構(gòu)設(shè)計(jì))
- C++實(shí)現(xiàn)LeetCode(169.求大多數(shù))
- C++實(shí)現(xiàn)LeetCode(309.買股票的最佳時(shí)間含冷凍期)
相關(guān)文章
c語(yǔ)言中字符串函數(shù)(庫(kù)函數(shù)使用)和模擬實(shí)現(xiàn)圖文教程
C++使用數(shù)組來(lái)實(shí)現(xiàn)哈夫曼樹(shù)
QT Creator+OpenCV實(shí)現(xiàn)圖像灰度化的示例代碼
C++實(shí)現(xiàn)中綴轉(zhuǎn)后綴的示例詳解
C語(yǔ)言實(shí)現(xiàn)通用數(shù)據(jù)結(jié)構(gòu)之通用椎棧

