잡다한 코딩/Project Euler (Java)

(Java) Project Euler 016 - Power Digit Sum

Skyleester_devNurse 2023. 12. 25. 18:00
// 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
// What is the sum of the digits of the number 2^1000?

 

Question)

-- 2^15 = 32768이고, 각 자릿수를 더하면 3 + 2 + 7 + 6 + 8 = 26이다.

-- 2^1000의 각 자릿수의 합은 무엇인가?

 

public class ProjectEuler_016 {
    public static void main(String[] args) {
        // BigInteger를 사용하여 2의 1000승을 계산.
        BigInteger value = BigInteger.valueOf(2).pow(1000);

        // 결과값을 문자열로 변환.
        String str = value.toString();
        int sum = 0;

        // 각 자리 숫자를 더하기.
        for (int i = 0; i < str.length(); i++) {
            sum += str.charAt(i) - '0';
        }
        
        System.out.println("The sum of digit is " + sum);
    }
}