注意每个阶乘只能用一次

Sum of Factorials

https://www.nowcoder.com/practice/42cb1c7f7344466b8cb1710cb12d06b1

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        int[] factorials = new int[10];
        factorials[0] = 1;
        for (int i = 1; i < 10; i++) {
            factorials[i] = factorials[i - 1] * i;
        }
        Scanner sc = new Scanner(System.in);
        Label:
        while (sc.hasNextInt()) {
            int n = sc.nextInt();
            int i = 9;
            while (i >= 0 && factorials[i] > n) --i;
            while (i >= 0) {
                if (n >= factorials[i]) {
                    n -= factorials[i];
                }
                if (n == 0) {
                    System.out.println("YES");
                    continue Label;
                }
                --i;
            }
            System.out.println("NO");
        }
    }
}

全部评论

相关推荐

评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务