在 N 中找到第一个非零数!在 Java

Find first non zero number in N! in Java

如何找到 N 的阶乘的第一个非零数。N 的范围可以从 1 到 2147483647。输出 return 一个整数。

例如:

findFirstNoneZeroNumberOfTheFactorial(4) = 4; // because 4! = 24
findFirstNoneZeroNumberOfTheFactorial(5) = 2; // because 5! = 120

这是我的代码:

import java.math.BigInteger;

public class Solution {
    public static int findFirstNoneZeroNumberOfTheFactorial(int n) {
        BigInteger fact = null;
        for (int i = 1; i <= n; i++) {
            fact = fact.multiply(BigInteger.valueOf(i));
        }
        String sFact = String.valueOf(fact);
        for (int i = sFact.length() - 1; i >= 0; i--) {
            if (sFact.charAt(i) != '0') {
                int result = Character.getNumericValue(sFact.charAt(i));
                return result;
            }
        }
        return 0;
    }
    public static void main(String[] args){
        System.out.println(Solution.findFirstNoneZeroNumberOfTheFactorial(4));
    }
}

但是不行!!

您忘记初始化 fact 变量,这导致 NullPointerException

改变

BigInteger fact = null;

BigInteger fact = BigInteger.ONE;

System.out.println(Solution.findFirstNoneZeroNumberOfTheFactorial(4)); 的输出:

4

不是将其转换为模块操作的字符串检查,如果它不为零,这就是您的答案,否则除以 10。

public static int findFirstNoneZeroNumberOfTheFactorial(int n) {
    long fact = 1L;
    for (int i = 1; i <= n; i++) {
        fact = fact * i;
    }
    while (fact > 0) {
        long module = fact % 10;
        if (module != 0) {
            return module;
        }
        fact = fact / 10;
    }
    return -1;

}

你的初始化不正确。

BigInteger fact = BigInteger.ONE;

This is not optimal. If you just need the single last non-zero digit just keep track only the last non zero digit not the whole multiplied number.

let's do some math
x     x!      last-nonzero-digit(x * last-nonzero-digit)
1     1             1*1        => 1
2     2             2*1 = 2    => 2
3     6             3*2 = 6    => 6 
4     24            6*4 = 2(4) => 4
5     120           4*5 = (2)0 => 2 
6     720           2*6 = 1(2) => 2
7     5040          2*7 = 1(4) => 4

为什么我必须计算整个乘法?

只保留最后一个非零数字。

这样对吗??

public static int number(int n) {
        int LastNoneZero = 1;
        for (int i = 1; i <= n; i++) {
            LastNoneZero *= i;
            if (LastNoneZero > 9) {
                String s = Integer.toString(LastNoneZero);
                if (s.charAt(1) == '0') {
                    LastNoneZero = Character.getNumericValue(s.charAt(0));
                } else {
                    LastNoneZero = Character.getNumericValue(s.charAt(1));
                }
            }
        }
        return LastNoneZero;
    }