Sum of Digits

Easy
0/40
Average time to solve is 15m
11 upvotes
Asked in companies
ProtiumMorgan StanleySamsung

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.

Detailed explanation ( Input/output format, Notes, Images )
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.
Sample Input 1:
2
3
10
Sample Output 1:
3
1
Sample Explanation:
For the first test case:-
3 is less than 10. Hence we cannot apply the operation.
Thus answer is 3.

For the second test case:-
N = 10
Replace N with 1 + 0 = 1
N = 1
1 is less than 10. Hence we cannot apply the operation.
Thus answer is 1.
Sample Input 2:
2
13
14
Sample Output 2:
4
5
Hint

Try to get sum of all digits.

Approaches (2)
Brute Force 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.
Time Complexity

O(log10(N)) where ‘N’ is the given number.

 

We are traversing the digits of a number until it becomes less than 10. The total number of maximum digits is log10(N). Hence time complexity will be O(log10(N)).

Space Complexity

O(1).

 

We are using constant space to solve this.

Code Solution
(100% EXP penalty)
Sum of Digits
Full screen
Console