求一個數的階乘後面有多少個0

Given an integer n, return the number of trailing zeroes in n!.

Note: Your solution should be in logarithmic time complexity.

Solutions:

n!可以分解爲n!=2x*3y*5z*....。可以得知結果中0的個數取決於5z*。

(1,n)的數中可以被5整除的有[n/5]個。

要注意的是25=5×5,出現一次就多了2個0,但計算的時候不會cnt += 2×[n/25],因爲5已經計算過一次。只需加1.

class Solution {
public:
	int trailingZeroes(int n){
		if(n <= 1) {
			return 0;
		}
		int cnt=0, base=5;
		while(base <= n) {
			cnt += n/base;
			base *= 5;
		}
		return cnt;
	}
};

但是在LC上超時。

(1,n)有多少能整除125的相當於n/5有多少能整除5的。執行通過。

class Solution {
public:
	int trailingZeroes(int n){
		if(n <= 1) {
			return 0;
		}
		int cnt=0;
		while(n > 0) {
			cnt += n/5;
			n /= 5;
		}
		return cnt;
	}
};



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章