简体   繁体   中英

Project Euler 20, Can someone tell me why my output is not correct?

public class ProjectEulerProblem20_Factorial_Digit_Sum {

public static void main(String[] args) {
    BigInteger oneHundredFactorial = BigInteger.ONE;
    for (int i = 100; i >= 1; i--) {
        oneHundredFactorial = oneHundredFactorial.multiply(BigInteger.valueOf(i));
    }       

    String k = oneHundredFactorial.toString();
    char x;
    int sum = 0;

    for (int i = 0; i < k.length(); i++) {
        x = k.charAt(i);
        sum = sum + x;
    }

    System.out.println(sum);
}

}

I do not see where I am going wrong here. My output should be the sum of all the digits in 100!. However, I have no idea why my value for sum is 8232, when the correct answer is 648. The code seems pretty basic to me and it seems to make sense. If anyone can help me out with what I seem to be missing out on that would be greatly appreciated. Thanks!

EDIT: This is the problem:

n! means n × (n − 1) × ... × 3 × 2 × 1

For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.

Find the sum of the digits in the number 100!

You are adding the ascii character value, when you want to add the digit value.

sum = sum + x;

Could use Character.digit(char, int) like

sum = sum + Character.digit(x, 10);

or

sum += Character.digit(x, 10);

or

sum += x - '0';

you're adding the character codes rather than the digits; you can use Character.getNumericValue to solve the problem at hand.

change your loop to this:

for (int i = 0; i < k.length(); i++) {
     sum = sum + Character.getNumericValue(k.charAt(i));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM