Amazon Interview Solution: Repetitive Addition Of Digits


Question
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
Input:
The first line contains 'T' denoting the number of testcases. Then follows description of testcases. The next T lines contains a single integer N denoting the value of N.

Output:
Output the sum of all its digit until the result has only one digit.

Constraints:
1<=T<=30
1<=n<=10^9

Example:
Input :
2
1
98


Output :
1
8

Explanation:  For example, if we conisder 98, we get 9+8  = 17 after first addition. Then we get 1+7 = 8.  We stop at this point because we are left with one digit.

Solution : There are some possible solutions. But here, the best solution is given. There is a pattern. If the number is divisible by 9 then the answer will be 9. If not then the answer will be n mod 9 .

Code

#include<iostream>
using namespace std;
int main()

{
    //code
    long long int i,j,k,l,m,n,t;
    cin>>t;
    for(i=1;i<=t;i++)
    {
        cin>>n;
        if(n%9==0)
        {
            cout<<9<<endl;
        }
        else
        {
            cout<<n%9<<endl;
        }
    }
    return 0;
}






Share on Google Plus
Earn @ Wap4dollar.Com

About Ashadullah Shawon

I am Ashadullah Shawon. I am a Software Engineer. I studied Computer Science and Engineering (CSE) at RUET. I Like To Share Knowledge.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment