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 % 10 is the last digit, n / 10 removes 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
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.