public class PowerOfTwoDigitSum {
public static String calculate2PowerNAsString(int N) {
// Calculate 2^N as a string for large numbers
StringBuilder result = new StringBuilder("1");
for (int i = 0; i < N; i++) {
int carry = 0;
for (int j = 0; j < result.length(); j++) {
int digit = result.charAt(j) - '0';
int num = digit * 2 + carry;
result.setCharAt(j, (char) ((num % 10) + '0'));
carry = num / 10;
}
while (carry > 0) {
result.append((char) ((carry % 10) + '0'));
carry /= 10;
}
}
return result.toString();
}
public static int sumOfDigits(int N) {
String result = calculate2PowerNAsString(N);
int sum = 0;
for (int i = 0; i < result.length(); i++) {
sum += result.charAt(i) - '0';
}
return sum;
}
public static void main(String[] args) {
int N = 15;
System.out.println("Sum of digits of 2^" + N + " is: " + sumOfDigits(N));
N = 100;
System.out.println("Sum of digits of 2^" + N + " is: " + sumOfDigits(N));
N = 1000;
System.out.println("Sum of digits of 2^" + N + " is: " + sumOfDigits(N));
}
}
/*
run:
Sum of digits of 2^15 is: 26
Sum of digits of 2^100 is: 115
Sum of digits of 2^1000 is: 1366
*/