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.
這道題并沒有什么難度,是讓求一個(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; } }
這題還有遞歸的解法,思路和上面完全一樣,寫法更簡潔了,一行搞定碉堡了。
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)容請搜索腳本之家以前的文章或繼續(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.二叉搜索樹迭代器)
- 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)文章
OpenCV3實(shí)現(xiàn)車牌識(shí)別(C++版)
這篇文章主要為大家詳細(xì)介紹了OpenCV3實(shí)現(xiàn)車牌識(shí)別功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-08-08可能是全網(wǎng)最詳細(xì)的Qt連接MySQL數(shù)據(jù)庫教程
QT眾所周知是一個(gè)開源的,以C++為底層的可視化工具庫,下面這篇文章主要給大家介紹了關(guān)于最詳細(xì)的Qt連接MySQL數(shù)據(jù)庫教程的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-04-04c++ 如何在libuv中實(shí)現(xiàn)tcp服務(wù)器
這篇文章主要介紹了c++ 如何在libuv中實(shí)現(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-09C語言實(shí)現(xiàn)個(gè)人通訊錄管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了C語言實(shí)現(xiàn)個(gè)人通訊錄管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-12-12VC++簡單實(shí)現(xiàn)關(guān)機(jī)、重啟計(jì)算機(jī)實(shí)例代碼
這篇文章主要介紹了VC++簡單實(shí)現(xiàn)關(guān)機(jī)、重啟計(jì)算機(jī)實(shí)例代碼,很實(shí)用的功能,需要的朋友可以參考下2014-07-07