-2

I have the correct code, I found an answer long ago, however I still don't understand why it works.

class Main {
    public static void main(String[] args) {
        System.out.println(D5PSum(10));
    }

    private static int D5PSum(int number) {
        String n = Integer.toString(number);
        int sum = 0;
        for (int i = 0; i < n.length(); i++) {
            // (1) WHY DOES THIS NOT WORK
            //sum += Integer.parseInt(number.charAt(i));

            // (2) MORE IMPORTANTLY WHY DOES THIS WORK
            char c = n.charAt(i);
            sum += (c-'0');
            // (3) WHAT IN THE WORLD IS c-'0'
        }
        return sum;
    }
}
3
  • 1
    integer-arithmetic-in-java-with-char-and-integer-literal Commented Jun 19, 2017 at 7:09
  • 1
    I suggest you go with debugger line by line. Commented Jun 19, 2017 at 7:09
  • @Jeremy Grand c - '0' results in a char, not a int. A char is basically a numeric type which represents a number between 0 and 65535 Commented Jun 19, 2017 at 7:25

8 Answers 8

1

// (1) WHY DOES THIS NOT WORK

because Integer.parseInt(...); is expecting a string as parameter not a char

// (2) MORE IMPORTANTLY WHY DOES THIS WORK

char c = n.charAt(i);

any char is nothing else as an integer mapped to a table of symbols...(ASCII table for example) so this (c - '0') is just another valid mathematical operation

Sign up to request clarification or add additional context in comments.

1 Comment

I have chosen c as just an example. I'm not refering the variable c here.
0
  1. charAt is not a valid method of the primitive type int.

  2. '0' is the character 0, and the character encoding set that Java uses has 0 to 9 in a consecutive block. Therefore c - '0' yields the position of c in that consecutive block which is therefore the value of the digit. (Actually this sort of thing is idiomatic C - goes right back to the 1960s).

Comments

0

You should first convert String to Int.. Please check the below code:

 class MainClass {
        public static void main(String[] args) {
            System.out.println(D5PSum(11));
        }

        private static int D5PSum(int number) {
            String n = Integer.toString(number);
            System.out.println(n);
            int sum = 0;
            for (int i = 0; i < n.length(); i++) {
                // (1) WHY DOES THIS NOT WORK
                String str = String.valueOf(n.charAt(i));
                sum += Integer.parseInt(str);

                // (2) MORE IMPORTANTLY WHY DOES THIS WORK
    //            char c = n.charAt(i);
    //            sum += (c-'0');
                // (3) WHAT IN THE WORLD IS c-'0'
            }
            return sum;
        }
    }

1 Comment

You can also do sum += Character.digit(n.charAt(i), 10);.
0

1 It doesnt work because Integer.parseInt takes a String and String.charAt returns a char(actar). Integer.parseInt (Character.toString(n.charAt(i))) would Work.

2/3 A char represents a number between 0 and 65535. EACH digit-characters (0-9) has a number in that range which depends on the charset. All digits are typically in a row, for example the character 0 has the value 48, 1 49 and 9 57. So ich you want to know the digit value of a char you simply subtract the character value of 0 from your character. That is the Line c-'0'

Comments

0
        // (1) WHY DOES THIS NOT WORK
        //sum += Integer.parseInt(number.charAt(i));

number is a variable of primitive data type "int" so number.charAt(i) won't work.

        // (2) MORE IMPORTANTLY WHY DOES THIS WORK
        char c = n.charAt(i);

n is an instance of String and we are getting the character at i th position in the n string

        sum += (c-'0');
        // (3) WHAT IN THE WORLD IS c-'0'

for every character there is an ascii code assigned. '0' = 48, 'c' = 99. That's the reason why it works here. when 'c'-'0' is executed, it's equivalent to 99-48

1 Comment

I have chosen c as just an example. I'm not referring the variable c here.
0

Why convert to a string in the first place? The simplest and fastest way to solve this is without deviation to strings:

private static int D5PSum(int number) {
    int v = number, sum = 0;
    while (v != 0) {
        sum += v % 10;
        v /= 10;
    }
    return sum;
}

Comments

0

If you want your code (the part which does not works to work then do this).

class Main {
    public static void main(String[] args) {
        System.out.println(D5PSum(10));
    }

    private static int D5PSum(int number) {
        String n = Integer.toString(number);
        int sum = 0;
        for (int i = 0; i < n.length(); i++) {

            sum += Integer.parseInt(n.charAt(i)+"");


        }
        return sum;
    }
}

1 Comment

@Henry thanks it was a silly mistake i couldn't have caught. now i have edit my answer
0

To get sum of the digits of a string str:

int sum = str.chars().map(Character::getNumericValue).sum();

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.