Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Euler 20 - Sum digits in 100! ( JAVA )

Can't seem to debug the following code. I believe the factorial method is correct. There must be an error somewhere in between converting it to a String and then adding up the individual characters.

Please add any extra recommendations on how to make the code more legible or perhaps faster.

Thanks

package euler20;

import java.math.BigInteger;

public class sumDigitsIn100Factorial {


        public static final int n = 100;

        public static void main(String[] args) {

            long startTime = System.currentTimeMillis();

            System.out.println("100! = " + factorial(n));
            System.out.println("Sum of all digits in 100! = " + sumOfDigits(factorial(n)));

            long endTime = System.currentTimeMillis();
            System.out.println("Time: " + (endTime - startTime) + " ms");

        }

        public static BigInteger factorial(int n1) {

            BigInteger n = BigInteger.ONE;

            for (int i = 1; i <= n1; i++) {
                n = n.multiply(BigInteger.valueOf(i));
            }
            return n;
        }

        public static int sumOfDigits(BigInteger n1) {

            String bigIntStr = factorial(n).toString();
            int sum = 0;

            for (int i = 1; i <= bigIntStr.length(); i++) {
                sum += Integer.parseInt(String.valueOf(i));
            }
            return sum;
        }
}