Sum of the digits of a number
Description: Write a method which returns the sum of the digits of a positive number. For 9475 the answer is 25.
Hint:
n % 10is the last digit,n / 10removes it.
Solution
public class Main {
static int digitSum(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
public static void main(String[] args) {
System.out.println(digitSum(9475));
System.out.println(digitSum(100));
System.out.println(digitSum(0));
}
}
Output
25
1
0
How it works
- The loop takes the last digit, adds it, and removes it, until the number becomes 0.
Read Java while Loop.
Learn more about the similar topics:
| Tutorials |
|---|
| Java if, else and else if |
| Java switch Statement and Expression |
| Java for Loop |
| Java while and do while Loop |
| Java break and continue |
| Exercises & Assignments |
|---|
| Find the largest of three numbers |
| Check if a year is a leap year |
| FizzBuzz in Java |
| Sum of the digits of a number |
| Print a multiplication table |
| Check if a number is prime |
| Interview Questions & Answers |
|---|
| No Content Found. |