Question:
Write a Java method called sumOfDigits
that takes an integer as a parameter and returns the sum of its digits.
The signature of the method is as follows:
public static int sumOfDigits(int num)
sumOfDigits(12345)
returns 15
Explanation:
The given number is 12345
.
The sum of its digits is 1 + 2 + 3 + 4 + 5 = 15
.
Therefore, the method should return 15
.
- Note: Assumption is that the input number will always be positive.
Implement the provided method sumOfDigits
in Java, using loops and arithmetic operations, to compute the sum of the digits of a given number.
Here is one possible solution for the sumOfDigits
method:
public static int sumOfDigits(int num) {
int sum = 0;
// Iterate through each digit of the number
while (num != 0) {
// Get the last digit of the number
int digit = num % 10;
// Add the digit to the sum
sum += digit;
// Update the number by removing the last digit
num /= 10;
}
// Return the final sum of the digits
return sum;
}
Let's walk through the code step-by-step:
sum
to store the sum of digits, and set it to 0
.0
.%
) of the number with 10
.+=
).10
, which removes the last digit.sum
will contain the sum of all the digits.sum
as the final result.By implementing this method, we can successfully calculate the sum of digits for any positive integer.
Make sure to test your sumOfDigits
method with various input values to ensure it behaves as expected.