LUCKYLUFFY的个人博客分享 http://blog.sciencenet.cn/u/LUCKYLUFFY

博文

尾部的零

已有 2090 次阅读 2017-12-15 07:15 |个人分类:ACM-LintCode|系统分类:科研笔记

问题描述:

设计一个算法,计算出n阶乘中尾部零的个数


解决思路:

计算阶乘,然后统计尾部0的个数。该方法导致内存溢出。


解决方案:

class Solution:

   """

   @param: n: An integer

   @return: An integer, denote the number of trailing zeros in n!

   """

   def trailingZeros(self, n):

       # write your code here, try to do it without arithmetic operators.

       temp = 1

       for i in range(1,n+1):

           temp *= i

       count = 0

       while(not temp % 10):

           temp /= 10

           count += 1

       return count


解决思路:

显然,如果结尾是0,那么是因为乘了5或者5的倍数。所以这个这个可以通过观察的方法得到。

输出[1,100]的结果

1 0

2 0

3 0

4 0

5 1

6 1

7 1

8 1

9 1

10 2

11 2

12 2

13 2

14 2

15 3

16 3

17 3

18 3

19 3

20 4

21 4

22 4

23 4

24 4

25 6

26 6

27 6

28 6

29 6

30 7

31 7

32 7

33 7

34 7

35 8

36 8

37 8

38 8

39 8

40 9

41 9

42 9

43 9

44 9

45 10

46 10

47 10

48 10

49 10

50 12

51 12

52 12

53 12

54 12

55 13

56 13

57 13

58 13

59 13

60 14

61 14

62 14

63 14

64 14

65 15

66 15

67 15

68 15

69 15

70 16

71 16

72 16

73 16

74 16

75 18

76 18

77 18

78 18

79 18

80 19

81 19

82 19

83 19

84 19

85 20

86 20

87 20

88 20

89 20

90 21

91 21

92 21

93 21

94 21

95 22

96 22

97 22

98 22

99 22

100 24

观察,突变的行

1 0=1/5

5 1=1+0=5/5 + 5/5/5

10 2=2+0=10/5+10/5/5

15 3=3+0=15/5+15/5/5

20 4=4+0=20/5+20/5/5

25 6=5+1+0=25/5+25/5/5+25/5/5/5

30 7=6+1+0=30/5+30/5/5+30/5/5/5

35 8=7+1+0=35/5+35/5/5+35/5/5/5

40 9=8+1+0=……

45 10=9+1+0=……

50 12

55 13

60 14

65 15

70 16

75 18

80 19

85 20

90 21

95 22

100 24

显然,方法是:n除以5的结果,然后将结果继续除以5,直到结果等于0,将所有的结果相加即为所求。


解决方案:

class Solution:

   """

   @param: n: An integer

   @return: An integer, denote the number of trailing zeros in n!

   """

   def trailingZeros(self, n):

       # write your code here, try to do it without arithmetic operators.

       count = 0

       while n / 5:

           count += n / 5

           n /= 5

       return count



https://blog.sciencenet.cn/blog-3373964-1089740.html

上一篇:谷歌浏览器最好用的翻译插件
下一篇:windows max path导致的问题ValueError: source code string ...
收藏 IP: 61.149.11.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-9-27 07:43

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部