Find Sum of all Digits of a Number

Objective: Given a number, find the sum of all of the digits in the number.

Example:

Number = 3045
Sum = 3+0+4+5 = 12

Number = 231
Sum = 2+3+1 = 7

Approach:

  1. Initialize sum =0.
  2. While number is greater than 0
    1. Divide the number by 10 and Add remainder the sum
N = 123, Sum = 0
N = N/10 => 123/10, N = 12, remainder = 3, sum = 3
N = N/10 => 12/10, N = 1, remainder = 2, sum = 3+2 = 5
N = N/10 => 1/10, N = 0, remainder = 1, sum = 3+2+1 = 6

Java Code:

public class SumOfDigits {
public static void digitsSums(int number){
int sum = 0;
int n = number;
while(n>0){
sum += n%10;
n = n/10;
}
System.out.println("Sum of digits of number " + number + " is: " + sum);
}
public static void main(String[] args) {
int number = 3045;
digitsSums(number);
}
}

view raw
SumOfDigits.java
hosted with ❤ by GitHub

Output:

Sum of digits of number 3045 is: 1