Search code examples
javaloopsbluej

Can't understand logic of code to find the sum of the evenly positioned digits


So basically the question is something like:

Write a program to accept a number from the user and find the sum of the evenly positioned digits counting from the left. For eg. if input is 94852 then output is 9(4+5).

Now, I am aware that this question can be done by converting the number to a string and using arrays, but in fact there is a better way of doing it.

The following program demonstrates the method -:

public class Question {
    public static void main(int a) {
        int evenSum = 0, oddSum = 0;
        int b = a; //b is used as a's value eventually becomes 0.
        while(a>0) { 
           int sum = evenSum + a % 10; 
           evenSum = oddSum; //Switching sums(?)
           oddSum = sum; //Interestingly,oddSum stores the sum of the oddly positioed digits
           a = a / 10; 
        }   
        System.out.println("The number entered is "+b);
        System.out.println("The even sum is " + evenSum);
    }
}

I happened to come across this answer when I was scouting for alternate solutions, and it left me stunned. I just couldn't understand the logic.

So can someone please explain what this method does and why it works?


Solution

  • The code repeatedly shifts a digit to the right (integer division by 10). It picks the right most digit by modulo 10 (remainder of integer division).

    It alternatively in the loop in one step sums in the one sum variable, in the next step in the other sum variable.

    So one has two sums: of "odd" and "even" digits.

    However as you name "odd" and "even" for positions from the left, and the loop starts from the right, you cannot say at the first step, first digit, wether that digit is at an odd or even position (counting from the left).

    Hence you need to sum both odd and even positions.

    And by swapping odd and even sums in every step, you ensure that always the momently last digit is added to the oddSum, evenSum indeed is the "even" sum.