Trailing Zeros算法

Trailing Zeros算法

该算法用于计算n的阶乘中尾部所包含零的个数;

举例

示例1:当n为5时
Input : 5;
Output : 1
Explanation:5! =120,120的尾部有1个0,所以输出应该为1;
示例2:当n为11时
Input : 11;
Ouput : 2;
Explanation : 11! = 39916800,结尾有2个0,所以输出应该为2;

实现

这是在领扣的Java IDE上进行编译后的结果截图

Trailing Zeros算法

代码实现


    // trailing zeros 
    /*
    *author:Roxanne;
    *date:2019/5/6
    *function:compute the number of zeros in n factorial;
    */
    import java.util.Scanner;
    public class Solution {
        public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入n:");
        long n = sc.nextInt();
        System.out.println(trailingZeros(n));
        }
      
        public static long trailingZeros(long n) {
            long count = 0;
            while(n != 0 ){
                count = n/5 + count;
                n = n/5;
            }
            return count;
        }
    }

注意事项

这里用scanner函数来获取n输入值;