zoukankan      html  css  js  c++  java
  • leetcode Factorial Trailing Zeroes

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

    Note: Your solution should be in logarithmic time complexity.

    Credits:
    Special thanks to @ts for adding this problem and creating all test cases.

    Subscribe to see which companies asked this question

     
    这种题就是找规律,对我来说就是这样;刚开始想简单了认为判断(n*n-1)%10==0如果是就加1,这明显6!都不符合。
    后来发现基本上就是遇5加1,但是100也不符合,100有20个5,期待值却是24;这4是什么呢,后来发现是有4个25;
    所以其实是5进制的感觉,虽然最终没有找到规律。就像25有5个5,但是期待值是6,所以就是遇5进1;
     
    所以最后我是用了一个循环,先求log(5)n,例如log(5)100=2.8几的,取2;于是只要看5的1次方和5的2次方,即有几个5,有几个25.
    假如是1000的话,log(5)1000=4.29,取4,所以看5,25,125,625,看1000分别有几个5,几个25,几个125,几个625.
     
    我发现这种和期待值对比的方法,,,容易让人找规律,不过这道题总结起来就是遇5加1!
    C++中求对数的方法:n=log(a)b   也就是n=log(b)/log(a)  
     
     
     1 class Solution {
     2 public:
     3     int trailingZeroes(int n) {
     4         int m=0,result=0;
     5         int count=log(n)/log(5);
     6         for(int i=1;i<=count;i++){
     7             m=pow(5,i);
     8             result+=n/m;
     9         }
    10         return result;
    11 
    12         }
    13 };
  • 相关阅读:
    array_keys
    strval
    is_numeric
    php static延迟静态绑定
    page39 类的访问权限控制
    page34类的继承
    被遗忘在角落的类型检查函数
    2.2.5重写静态变量
    2.2.3使用parent作用域
    16个最棒的WordPress博客写作发布工具【博主桌面工具】
  • 原文地址:https://www.cnblogs.com/LUO77/p/5004837.html
Copyright © 2011-2022 走看看