- The function,
sumDigits
should return the sum of digits of the parameter, n
. For this, you can add each digit of n
to a variable, sum
initialized with the value, 0
. The value of x % 10
gives you the last digit of x
. Every time you add the last digit of n
to sum
, divide it by 10
to make it one digit less from the end.
- You need a loop to pass the sum of digits to
sumDigits
until the sum of digits become a single digit. I suggest you use a do-while
loop which guarantees its body to be executed at least once.
- At the end of the loop mentioned in point#2, you will have the sum of digits as a single digit. The final thing that you need to do now is to check if this sum is divisible by
9
.
Note that if x % y == 0
, then x
is divisible by y
.
Demo:
public class Main {
public static void main(String[] args) {
int n = 123456789;
int singleDigitSum = 0;
int divisibleBy = 9;
do {
singleDigitSum = sumDigits(n);
n = singleDigitSum;
} while (singleDigitSum > 9);
if (singleDigitSum % divisibleBy == 0) {
System.out.println("The single digit sum is divisible by " + divisibleBy);
} else {
System.out.println("The single digit sum is divisible by " + divisibleBy);
}
}
private static int sumDigits(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
}
Output:
The single digit sum is divisible by 9
Note: Java does not allow defining a method/function inside another method/function. You have done this mistake by defining the function, sumDigits
inside the method, main
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…