0

for Example:

2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26

but i does not get desired results

when i add all char it gives output as: 266

import java.util.Scanner;

public class ProjectEu {
  public static void main(String...rDX) {
    int degree = new Scanner(System.in).nextInt();
    String store = Integer.toString((int)Math.pow(2,degree));
    char [] finals  = store.toCharArray();

    int temp = 0;
    for (int i = 0, n = store.length(); i < n; i++) {
        System.out.printf("values[%d] --> %c \n",i, finals[i]);
        temp = temp + finals[i];
    }

    System.out.println(temp);
 }
}
2
  • Pratik did my answer help you? Commented Nov 23, 2018 at 18:38
  • Pratik Katariya, if my answer helped you can you please mark it as accepted? Commented Dec 20, 2018 at 20:13

4 Answers 4

1

The reason that you are getting this error is because temp is an integer, but finals[i] is a character, so it converts the characters into ASCII values and adds them. You can fix this problem by doing:

for (int i = 0, n = store.length(); i < n; i++) {
    char ch = store.charAt(i);
    int digit = Integer.parseInt(Character.toString(ch));
    temp = temp + digits;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

int sum = store.chars()
               .boxed()
               .map(Character::getNumericValue)
               .mapToInt(Integer::intValue)
               .sum();

Comments

0

This line:

temp = temp + finals[i];

sums temp and the ASCII code of the char stored in finals[i].
You can get the value of the digit by this:

temp = temp + finals[i] - '0';

This means that by subtracting from the digit's ASCII code the ASCII code of 0 you get the number value of the digit.

Comments

0

When you are adding a character to an integer, you are adding the integer code of the character, not its actual numeric value .

What you need is Character.getNumericValue :

temp = temp + Character.getNumericValue(finals[i]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.