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?
Solution:
Again I've used BigInteger because 21000 doesn't fit inside long.
Here's the java code
import java.math.BigInteger; public class Prob16 { public static void main(String[] args) { int sum =0; int digit; BigInteger a = new BigInteger("1"); BigInteger b = new BigInteger("2"); for(int i = 1 ; i <= 1000 ; i++ ) { a = a.multiply(b); } String A = a.toString(); for(int i =0 ; i < A.length();i++) { digit = A.charAt(i) - '0'; sum = sum + digit; } System.out.println(sum); } }
why is that
ReplyDeletedigit = A.charAt(i) - '0';
I mean 0
I am converting each Ascii character value Numerical value, i.e to convert '1' to 1.
Deletethe ASCII value of '1' is 49 to convert it to Numerical 1, I am subtracting the ASCII value of the first digit, i,e '0' which has an ASCII value of 48,
Digit = '1' - '0';
which is similar to 49 - 48.