码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Day4——Factorial Trailing Zeroes

时间:2015-09-08 00:23:02      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

 1 /*
 2  * Problem 172: Factorial Trailing Zeroes
 3  * Given an integer n, return the number of trailing zeroes in n!.
 4  * Note: Your solution should be in logarithmic time complexity.
 5  */
 6 
 7  /*
 8   * Solution 1
 9   * 对于每一个数字,累计计算因子10、5、2数字出现的个数,结果等于10出现的个数,加上5和2中出现次数较少的
10   * 改进:5出现的次数一定大于2出现的次数,因此只需要统计因子10和5出现的次数。进一步衍生为只统计5出现的次数。
11   * 改进:讲循环控制的步长改为5
12   */
13 int trailingZeroes(int n) {
14     int number10 = 0;
15     int number5 = 0;
16     int number2 = 0;
17     
18     int temp;
19     for ( int i = n; i >=2; i--) {
20         temp = i;
21         while (temp >= 2) {
22             if ( temp % 10 == 0) {
23                 number10++;
24                 temp = temp/10;
25             } else if ( temp % 5 == 0) {
26                 number5++;
27                 temp = temp/5;
28 //            } else if (temp % 2 == 0) {
29 //                number2++;
30 //                temp = temp/2;
31             } else {
32                 break;
33             }
34         }
35     }
36     return (number5>number2?number2:number5)+number10;
37 }
38 
39 /*
40  * Solution 2
41  * 根据上面分析,只需要统计所有数字中因子5出现的次数
42  */
43 int trailingZeroes(int n) {
44     int result = 0;
45     int temp = n/5;
46     while (temp >= 1) {
47         result += temp;
48         temp = temp/5;
49     }
50     return result;
51 }

 

LeetCode Day4——Factorial Trailing Zeroes

标签:

原文地址:http://www.cnblogs.com/luop/p/4790330.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!