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ù)量又遠(yuǎn)大于5的數(shù)量(比如1到 10 中有2個5,5個2),那么此題即便為找出5的個數(shù)。仍需注意的一點就是,像 25,125,這樣的不只含有一個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; } }
這題還有遞歸的解法,思路和上面完全一樣,寫法更簡潔了,一行搞定碉堡了。
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++實現(xiàn)LeetCode(172.求階乘末尾零的個數(shù))的文章就介紹到這了,更多相關(guān)C++實現(xiàn)求階乘末尾零的個數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
可能是全網(wǎng)最詳細(xì)的Qt連接MySQL數(shù)據(jù)庫教程
QT眾所周知是一個開源的,以C++為底層的可視化工具庫,下面這篇文章主要給大家介紹了關(guān)于最詳細(xì)的Qt連接MySQL數(shù)據(jù)庫教程的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-04-04c++ 如何在libuv中實現(xiàn)tcp服務(wù)器
這篇文章主要介紹了c++ 如何在libuv中實現(xiàn)tcp服務(wù)器,幫助大家更好的理解和使用libuv,感興趣的朋友可以了解下2021-02-02C語言中獲取和改變目錄的相關(guān)函數(shù)總結(jié)
這篇文章主要介紹了C語言中獲取和改變目錄的相關(guān)函數(shù)總結(jié),包括getcwd()函數(shù)和chdir()函數(shù)以及chroot()函數(shù)的使用方法,需要的朋友可以參考下2015-09-09VC++簡單實現(xiàn)關(guān)機(jī)、重啟計算機(jī)實例代碼
這篇文章主要介紹了VC++簡單實現(xiàn)關(guān)機(jī)、重啟計算機(jī)實例代碼,很實用的功能,需要的朋友可以參考下2014-07-07