Last Updated: 16 Apr, 2021

Sum of Digits

Easy
Asked in companies
LinkedInWalmartMorgan Stanley

Problem statement

Ninja is given an integer ‘N’. One day Ninja decides to do the sum of all digits and replace the ‘N’ with the sum of digits until it becomes less than 10. Ninja wants to find what will be the value of ‘N’ after applying this operation.

Help Ninja in finding out this value.

Input Format:
The first line of input contains an integer ‘T’ denoting the number of test cases. 

The first and only line of the test case consists of a single integer ‘N’.
Output Format:
For each test case, print a single line containing a single integer denoting the final value of ‘N’.

The output of each test case will be printed in a separate line.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= ‘T’ <= 11
1 <= ‘N’ <= 10 ^ 9

Time Limit: 1 sec.

Approaches

01 Approach

The main idea is to do the sum of digits until it becomes less than 10.

 

Algorithm:

  • Add a condition if N is less than 10 then return N.
  • Do the sum of all digits.
  • Make a recursive call and pass the sum of digits as N.
  • Return the answer which you get from a recursive call.

02 Approach

Express the given number as 9 * K  +T. The divisibility rule of 9 states that if the given number is divisible by 9, then the sum of all digits is also divisible by 9. Express N as 9 * K + T. After calculating the sum of digits ‘N’ will become 9 * K + T since T is less than 9.  After applying the operation only T will be left in the end. Thus answer is T. If the number is divisible by 9 then in the end 9 will be left. Thus answer will be 9 in that case.

 

Algorithm:

  • If N is less than 9 return N.
  • If N % 9 == 0 then return 9.
  • Else return N % 9.