Be the first user to complete this post

  • 0
Add to List
Beginner

289. 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

Output:

Sum of digits of number 3045 is: 1