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:

Output:

Sum of digits of number 3045 is: 1

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

You may also like...

%d bloggers like this: