Power digit sum
Problem 16
215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 21000?
(https://projecteuler.net/problem=16)What is the sum of the digits of the number 21000?
Problem 16 is as easy as Problem 15, and really similar to Problem 15.
We are using BigInteger again, since 21000 is.... humongous.
BigInteger num = BigInteger.valueOf(2).pow(1000);
To calculate the sum of the digits, we will use a quick trick here.
Instead of converting each char of our BigInteger String, we will use the char itself.
How the computer deals with char is that char has its own number value.
Therefore, we don't know what value the char '1' has, but we know that '1' - '0' will return the numeric value of 1 because they are consecutive.
char[] arr = num.toString().toCharArray(); for (char c : arr) ans += c - '0';
Answer is 1366
Execution time is 2.681005 ms
Source Code: https://github.com/Ainodyne/Project-Euler/blob/master/Problem016.java
No comments:
Post a Comment