NC129. 阶乘末尾0的数量
描述
示例1
输入:
3
输出:
0
说明:
3!=6示例2
输入:
5
输出:
1
说明:
5!=120示例3
输入:
1000000000
输出:
249999998
C++ 解法, 执行用时: 2ms, 内存消耗: 332KB, 提交时间: 2020-11-01
class Solution { public: /** * the number of 0 * @param n long长整型 the number * @return long长整型 */ long long thenumberof0(long long n) { // write code here long long count = 0; while(n){ count += n/5; n /=5; } return count; if (n < 5) return 0; int res = 1; res = dfs(n); int num = 0; while(res % 10 == 0){ num++; } return num; } int dfs(int n){ if(n == 1){ return 1; } return n*dfs(n-1); } };
C++ 解法, 执行用时: 2ms, 内存消耗: 340KB, 提交时间: 2021-03-29
class Solution { public: /** * the number of 0 * @param n long长整型 the number * @return long长整型 */ long long thenumberof0(long long n) { // write code here long long out = 0;;; while(n) { out += n/5; n = n/5; } return out; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 344KB, 提交时间: 2021-05-16
class Solution { public: /** * the number of 0 * @param n long长整型 the number * @return long长整型 */ long long thenumberof0(long long n) { // write code here long long cnt=0; long long t=5; while(t<=n){ long long s=n/t; cnt+=s; t*=5; } return cnt; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 344KB, 提交时间: 2020-12-01
class Solution { public: /** * the number of 0 * @param n long长整型 the number * @return long长整型 */ long long thenumberof0(long long n) { // write code here if (0 == n) { return 1; } long long count = 0; while (n) { count = count + n / 5; n = n / 5; } return count; } // if (0 == n) // { // return 1; // } // long long sum = n; // long long count = 0; // while (n > 1) // { // sum = sum * (n - 1); // n--; // } // int i = 1; // while(sum != 0) // { // if (sum / i % 10 == 0) // { // count++; // } // sum = sum / 10; // } // return count; // } };
C++ 解法, 执行用时: 2ms, 内存消耗: 348KB, 提交时间: 2021-05-09
class Solution { public: /** * the number of 0 * @param n long长整型 the number * @return long长整型 */ //算阶乘数的方法不行。这样数太大了。发现有2的倍数和5或 乘数是10倍数时会产生末尾0(这是我想的) //其实就是数有多少个5就可以了,有多少个5就有多少个0,因为2个个数是足以匹配5的 long long thenumberof0(long long n) { // write code here //先算阶乘大小呗 long long num=5; long long count=0; while(num<=n){ count+=n/num; num*=5; } return count; } };