Repeated sum of digits

PROBLEM :

Given an integer N, recursively sum digits of N until we get a single digit.  The process can be described below

If N < 10  
    digSum(N) = N
Else        
    digSum(N) = Sum(digSum(N))
Example:

Input : 1234
Output : 1
Explanation : The sum of 1+2+3+4 = 10,
              digSum(x) == 10
              Hence ans will be 1+0 = 1
Input:

The first line contains an integer T, total number of test cases. Then following T lines contains an integer N.

Output:

Repeated sum of digits of N.

Constraints:

1 = T = 100

1 = N = 1000000

Example:

Input
2
123
9999

Output
6
9

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

#include<iostream>
using namespace std;
int Repeated_sum_of_digits(int ) ;
int sum_digits(int ) ;
int main()
 {
int t,no ;
cin>>t ;
while(t--)
{
   cin>>no ;
   cout<<Repeated_sum_of_digits(no)<<endl ;
}
return 0;
}

int Repeated_sum_of_digits(int no)
{
    if(no<10)
        return no ;
    else
        Repeated_sum_of_digits(sum_digits(no)) ;
}

int sum_digits(int no)
{
    int r,sum ;
    sum=0 ;
   
    while(no)
    {
        r=no%10 ;
        sum=sum+r ;
        no=no/10 ;
    }
    return sum ;
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )