Write a method digitSum that accepts an integer parameter and returns the sum of its digits

The correct answer and explanation is:

Here’s the correct implementation of the digitSum method in Java:

public static int digitSum(int number) {
    int sum = 0;
    while (number > 0) {
        sum += number % 10;  // Add the last digit to sum
        number /= 10;        // Remove the last digit
    }
    return sum;
}

Explanation (300 words)

The digitSum method calculates the sum of the digits of a non-negative integer. This is a common task in programming that helps reinforce understanding of loops, arithmetic operations, and number manipulation.

The core idea is to repeatedly extract the last digit of the number using the modulus operator (%), and then remove that digit using integer division (/).

Let’s break the logic down step by step:

  1. Initialization:
    We begin by initializing a variable sum to 0. This variable will keep track of the running total of the digits.
  2. Looping through the digits:
    A while loop is used to process each digit. The condition number > 0 ensures that we continue looping until all digits have been processed.
  3. Extracting the last digit:
    Inside the loop, number % 10 extracts the last digit of the number. For example, if number is 29107, 29107 % 10 equals 7. This digit is then added to sum.
  4. Removing the last digit:
    After extracting and adding the last digit, we remove it by dividing number by 10 using integer division (number /= 10). Integer division discards the remainder, so 29107 / 10 becomes 2910.
  5. Repeat:
    The loop repeats this process for each digit until number becomes 0.
  6. Return the result:
    Once the loop ends, sum contains the total of all the digits, and we return this value.

Example

For digitSum(29107), the loop adds:

  • 7 (29107 % 10)
  • 0 (2910 % 10)
  • 1 (291 % 10)
  • 9 (29 % 10)
  • 2 (2 % 10)
    Total = 2 + 9 + 1 + 0 + 7 = 19

This method is efficient and works for any non-negative integer.

By admin

Leave a Reply

Your email address will not be published. Required fields are marked *