题解 | 阶乘末尾非零数字

阶乘末尾非零数字

https://www.nowcoder.com/practice/248c8fbee56e491aa147b67b9c082da0

import java.util.*;

public class Main {
    static class Solution {
        public int lastNonZeroDigit(int n) {
            // n2表示因子2的个数,n5表示因子5的个数
            int n2 = 0, n5 = 0;
            // p记录其他因子相乘的最后一位
            int p = 1;
            
            // 遍历2到n的每个数
            for (int i = 2; i <= n; i++) {
                int temp = i;
                
                // 统计因子5的个数
                while (temp % 5 == 0) {
                    n5++;
                    temp /= 5;
                }
                
                // 统计因子2的个数
                while (temp % 2 == 0) {
                    n2++;
                    temp /= 2;
                }
                
                // 剩余因子相乘的最后一位
                p = (p * temp) % 10;
            }
            
            // 处理剩余的因子2
            for (int i = 0; i < n2 - n5; i++) {
                p = (p * 2) % 10;
            }
            
            return p;
        }
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        
        Solution solution = new Solution();
        System.out.println(solution.lastNonZeroDigit(n));
    }
}

全部评论

相关推荐

评论
3
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务