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:
- Initialization:
We begin by initializing a variablesumto 0. This variable will keep track of the running total of the digits. - Looping through the digits:
Awhileloop is used to process each digit. The conditionnumber > 0ensures that we continue looping until all digits have been processed. - Extracting the last digit:
Inside the loop,number % 10extracts the last digit of the number. For example, ifnumberis 29107,29107 % 10equals 7. This digit is then added tosum. - Removing the last digit:
After extracting and adding the last digit, we remove it by dividingnumberby 10 using integer division (number /= 10). Integer division discards the remainder, so29107 / 10becomes 2910. - Repeat:
The loop repeats this process for each digit untilnumberbecomes 0. - Return the result:
Once the loop ends,sumcontains 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.