C++實現(xiàn)LeetCode(172.求階乘末尾零的個數(shù))
[LeetCode] 172. Factorial Trailing Zeroes 求階乘末尾零的個數(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.
這道題并沒有什么難度,是讓求一個數(shù)的階乘末尾0的個數(shù),也就是要找乘數(shù)中 10 的個數(shù),而 10 可分解為2和5,而2的數(shù)量又遠大于5的數(shù)量(比如1到 10 中有2個5,5個2),那么此題即便為找出5的個數(shù)。仍需注意的一點就是,像 25,125,這樣的不只含有一個5的數(shù)字需要考慮進去,參加代碼如下:
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;
}
}
這題還有遞歸的解法,思路和上面完全一樣,寫法更簡潔了,一行搞定碉堡了。
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/
到此這篇關于C++實現(xiàn)LeetCode(172.求階乘末尾零的個數(shù))的文章就介紹到這了,更多相關C++實現(xiàn)求階乘末尾零的個數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
c語言中字符串函數(shù)(庫函數(shù)使用)和模擬實現(xiàn)圖文教程
C語言中對字符和字符串的處理很是頻繁,但是C語言本身并沒有字符串類型,這篇文章主要給大家介紹了關于c語言中字符串函數(shù)(庫函數(shù)使用)和模擬實現(xiàn)的相關資料,需要的朋友可以參考下2024-01-01
QT Creator+OpenCV實現(xiàn)圖像灰度化的示例代碼
這篇文章主要為大家詳細介紹了QT如何利用Creator和OpenCV實現(xiàn)圖像灰度化效果,文中的示例代碼講解詳細,感興趣的小伙伴可以嘗試一下2022-12-12
C語言實現(xiàn)通用數(shù)據(jù)結構之通用椎棧
這篇文章主要為大家詳細介紹了C語言實現(xiàn)通用數(shù)據(jù)結構之通用椎棧,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-11-11

