标签:
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
统计末尾0的个数,只需要统计2,5的个数就可以了
1 class Solution { 2 public: 3 int trailingZeroes(int n) { 4 5 int count2=0; 6 int count5=0; 7 8 for(int i=2;i<=n;i++) 9 { 10 int num=i; 11 while(num%2==0&&num>0) 12 { 13 count2++; 14 num=num/2; 15 } 16 17 18 while(num%5==0&&num>0) 19 { 20 count5++; 21 num=num/5; 22 } 23 } 24 25 return min(count2,count5); 26 } 27 };
[n/k]代表1~n中能被k整除的个数
那么很显然
[n/2] > [n/5] (左边是逢2增1,右边是逢5增1)
[n/2^2] > [n/5^2](左边是逢4增1,右边是逢25增1)
……
[n/2^p] > [n/5^p](左边是逢2^p增1,右边是逢5^p增1)
随着幂次p的上升,[n/2^p]会远大于[n/5^p]
因此左边的加和一定大于右边的加和,也就是n!质因数分解中,2的次幂一定大于5的次幂
1 class Solution { 2 public: 3 int trailingZeroes(int n) { 4 5 int count2=0; 6 int count5=0; 7 8 for(int i=2;i<=n;i++) 9 { 10 int num=i; 11 12 while(num%5==0&&num>0) 13 { 14 count5++; 15 num=num/5; 16 } 17 } 18 19 return count5; 20 } 21 };
1 class Solution { 2 public: 3 int trailingZeroes(int n) { 4 return get5(n); 5 } 6 7 int get5(int n) 8 { 9 if(n<5)return 0; 10 return n/5+get5(n/5); 11 } 12 };
【leetcode】Factorial Trailing Zeroes
标签:
原文地址:http://www.cnblogs.com/reachteam/p/4194023.html