Java From Beginner To Advanced

0% completed

Previous
Next
Sum of Digits at Even and Odd Places

Problem Statement

Write a Java program to calculate the sum of digits located at even positions and the sum of digits located at odd positions in a given number. Positions are counted from the right (least significant digit) starting at position 1. For example, in the number 12345, the digits at odd positions are 5, 3, and 1, and the digits at even positions are 4 and 2.

Examples

Example 1:

  • Input: number = 12345
  • Output:
    Sum of digits at odd positions: 9
    Sum of digits at even positions: 6
    
  • Justification:
    • Odd Positions:
      • Position 1: 5
      • Position 3: 3
      • Position 5: 1
      • Sum: 5 + 3 + 1 = 9
    • Even Positions:
      • Position 2: 4
      • Position 4: 2
      • Sum: 4 + 2 = 6

Example 2:

  • Input: number = 2468
  • Output:
    Sum of digits at odd positions: 6
    Sum of digits at even positions: 12
    
  • Justification:
    • Odd Positions:
      • Position 1: 8
      • Position 3: 4
      • Sum: 8 + 4 = 12
    • Even Positions:
      • Position 2: 6
      • Position 4: 2
      • Sum: 6 + 2 = 8

Step-by-Step Algorithm

To calculate the sum of digits at even and odd positions in a number, follow these steps:

  1. Initialize Variables:

    • Let number be the input number (of type long to accommodate large numbers).
    • Initialize two variables, sumOdd and sumEven, to 0. These will store the sums of digits at odd and even positions, respectively.
    • Initialize a variable position to 1 to keep track of the current digit's position (starting from the right).
  2. Handle Negative Numbers:

    • If the input number is negative, convert it to its absolute value to simplify processing.
  3. Iterate Through Each Digit:

    • Use a while loop to iterate as long as number is greater than 0.
    • In each iteration:
      • Extract the last digit using digit = number % 10.
      • Check the current position:
        • If position is odd, add the digit to sumOdd.
        • If position is even, add the digit to sumEven.
      • Remove the last digit from number using number = number / 10.
      • Increment the position by 1.
  4. Display the Results:

    • After the loop concludes, print the values of sumOdd and sumEven.

Code

Below is the Java code that demonstrates how to calculate the sum of digits at even and odd positions in a number. This example checks the number 12345.

Java
Java

. . . .

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next