|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Text; |
| 4 | + |
| 5 | +namespace LeetCode_172 |
| 6 | +{ |
| 7 | + //static void Main(string[] args) |
| 8 | + //{ |
| 9 | + // var solution = new Solution(); |
| 10 | + // while (true) |
| 11 | + // { |
| 12 | + // int input = int.Parse(Console.ReadLine()); |
| 13 | + // //string input = Console.ReadLine(); |
| 14 | + // //string input2 = Console.ReadLine(); |
| 15 | + // var res = solution.TrailingZeroes(input); |
| 16 | + // Console.WriteLine(res); |
| 17 | + // } |
| 18 | + //} |
| 19 | + public class Solution |
| 20 | + { |
| 21 | + /// <summary> |
| 22 | + /// 更高维度拆解分式,通过数学推出,大概思路就是分解25就是分解两次5,往上也是一样,所以通过不断分解5就可以得到答案 |
| 23 | + /// 时间复杂度O(log n),因为是不断除以5,所以是5的幂,即为O(log 5 n),循环内的除法是32位整形内的,所以是O(1),忽略 |
| 24 | + /// 空间复杂度O(1),只用了一个zeroCount计算。 |
| 25 | + /// </summary> |
| 26 | + /// <param name="n"></param> |
| 27 | + /// <returns></returns> |
| 28 | + public int TrailingZeroes(int n) |
| 29 | + { |
| 30 | + int zeroCount = 0; |
| 31 | + while (n > 0) |
| 32 | + { |
| 33 | + n /= 5; |
| 34 | + zeroCount += n; |
| 35 | + } |
| 36 | + return zeroCount; |
| 37 | + } |
| 38 | + |
| 39 | + /// <summary> |
| 40 | + /// 尾数的零一定是由2乘以5构成的,所以可以分解成有多少个2和5的组合就能获得答案,因为分解出来的2是远多于5的, |
| 41 | + /// 所以忽略掉2,只考虑5。5还有一种特殊情况就是,例如25这种,可以分解出不只一个5,这种就要特殊考虑。 |
| 42 | + /// 时间复杂度O(n),循环步长为5,所以是1/5n,还有部分进入计算的也可以忽略不计 |
| 43 | + /// 空间复杂度O(1),只用了一个zeroCount计数。 |
| 44 | + /// </summary> |
| 45 | + /// <param name="n"></param> |
| 46 | + /// <returns></returns> |
| 47 | + //public int TrailingZeroes(int n) |
| 48 | + //{ |
| 49 | + // //写到一半突然觉得不对,笔记本上写了一下,发现了规律。降维打击成就达成(然而并没有,哈哈哈) |
| 50 | + // int zeroCount = 0; |
| 51 | + // for (int i = 5; i <= n; i += 5) |
| 52 | + // { |
| 53 | + // int powerOfFive = 5; |
| 54 | + // while (i % powerOfFive == 0) |
| 55 | + // { |
| 56 | + // zeroCount++; |
| 57 | + // powerOfFive *= 5; |
| 58 | + // } |
| 59 | + // } |
| 60 | + // return zeroCount; |
| 61 | + //} |
| 62 | + } |
| 63 | +} |
0 commit comments