zoukankan      html  css  js  c++  java
  • n! 阶乘

    其实1、2、3、4、6、7…都是可以不用考虑的,因此选择以5为迭代步数即可。 
    首先,这些数字都可以不用进行%5(对5取余数)运算,因此每次循环时可以直接将函数的count变量直接加1。其次,考虑25、125、625…等5的幂次项,因为他们每一个都可以在与偶数相乘之后产生多个0。因此,设置一个循环体,判断是多少幂次项,并将结果加进count。 
    综上所述,可以编写代码如下:

    算法代码

     1 public class Solution {
     2 
     3     /*
     4      * param n: As desciption return: An integer, denote the number of trailing
     5      * zeros in n!
     6      */
     7     public long trailingZeros(long n) {
     8         // write your code here
     9         long count = 0;
    10         long pwr = 25;
    11         for (long temp = 5; temp <= n; temp+=5) {
    12             // for循环内部的temp都是5的倍数,因此首先进行+1操作
    13             count++;
    14             pwr = 25;
    15             // 判断是不是25、125、625...的倍数,并根据每次pwr的变化进行+1操作
    16             while (temp % pwr == 0) {
    17                 count++;
    18                 pwr *= 5;
    19             }
    20         }
    21         return count;
    22     }
    23 }
  • 相关阅读:
    bat 处理adb脚本
    作用域,高阶函数
    常用内置函数-6
    习题元祖与字典的值交换
    函数的参数
    序列类型与非序列类型
    格式化输出,深浅复制
    可变,不可变与 id 的关系
    linux-shell系列6-rundeck生成host文件
    linux-shell系列5-统计
  • 原文地址:https://www.cnblogs.com/wfq9330/p/9558456.html
Copyright © 2011-2022 走看看