頭一次遇上翻譯完了還沒看懂意思的題目,英文功底還是需要的啊=__=||
描述:
Given an integer n, return the number of trailing zeroes in n!.
就這麼一句話,意思是這樣:給出一個整數,int型,計算以這個整數開始的階乘n!,這個階乘得到的數中的尾部有多少個0.
我們可以知道10 = 2*5,也就是說從1到n中:一個尾數爲5和一個尾數爲2的數乘起來就有1個0。當然,分解開來還是5*2。
以10爲例子:1 2 3 4 5 6 7 8 9 10 ,包含2和爲2的數有多少個稍微瞟一眼就能知道了,總之很多;;而5呢?只有5和10 = 5×2總共2個。
這就不用說了,2本來的就能被大多數整除,那要找和5匹配的2是一抓一大把,那麼這裏我們得出一個結論:只需要找其中所有能被5整數的數,求得每一個數能被分解成多少個5的總數。
開始的代碼是這樣:
class Solution {
public:
int trailingZeroes(int n) {
if(n < 4){return 0;}
int time = 0;
while(n/5 != 0){
n /= 5;
time += n;
}
return time;
}
};
計算5的個數, SUM = N/5^1+N/5^2 +N/5^3+….
改進之後的代碼:
class Solution {
public:
int trailingZeroes(int n) {
return n==0?0:n/5 + trailingZeroes(n/5);
}
};
對於python有更多一種方法,因爲python支持自動將低長度的數字自動轉換成大數
同上的方法:
class Solution(object):
def trailingZeroes(self, n):
return (0 if n == 0 else (n/5+self.trailingZeroes(n/5)))
另外一種乘的方法:
class Solution(object):
def trailingZeroes(self, n):
time = 0
x = 5
while n >= x:
time += n/x
x *= 5 #在c++中使用這樣乘,很快就使得x超出int型的長度了,出錯,所以不能使用
return time
特別注意:Python會自動把大數轉化爲long類型,足夠應付比較大的輸入。