Write a method digitSum that accepts an integer parameter and returns the sum of its digits. Assume that the number is non-negative. Example: digitSum(29107) returns 2+9+1+0+7 or 19 Hint: Use the % operator to extract a digit from a number.
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:
- Initialization:
We begin by initializing a variablesum
to 0. This variable will keep track of the running total of the digits. - Looping through the digits:
Awhile
loop is used to process each digit. The conditionnumber > 0
ensures that we continue looping until all digits have been processed. - Extracting the last digit:
Inside the loop,number % 10
extracts the last digit of the number. For example, ifnumber
is 29107,29107 % 10
equals 7. This digit is then added tosum
. - Removing the last digit:
After extracting and adding the last digit, we remove it by dividingnumber
by 10 using integer division (number /= 10
). Integer division discards the remainder, so29107 / 10
becomes 2910. - Repeat:
The loop repeats this process for each digit untilnumber
becomes 0. - 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.