## Amazon Interview Question

Software Engineer / Developers```
int FindSum(int num){
//If num is single digit
int sum = 0;
if(num / 10 == 0)
return num;
else
{
while(num > 1){
sum = sum + num % 10;
num = num / 10;
}
//If sum is not single digit
if( sum / 10 != 0)
sum = FindSum(sum);
}
return sum;
}
int main( )
{
cout << FindSum(9999) << endl;
return 0;
}
```

Modifying Sachinsaner's code to make it work (Just added a >= for num>1)

int FindSum(int num){

//If num is single digit

int sum = 0;

if(num / 10 == 0)

return num;

else

{

while(num > 1){

sum = sum + num % 10;

num = num / 10;

}

//If sum is not single digit

if( sum / 10 != 0)

sum = FindSum(sum);

}

return sum;

}

int main( )

{

cout << FindSum(9999) << endl;

return 0;

}

```
public class SumofDigits {
public static int sumofdigits(int inputnum)
{
int quot = inputnum;
int rem = 0;
while(quot > 0)
{
rem = rem + (quot % 10);
quot = quot/10;
}
if(rem/10 > 0)
{
rem = sumofdigits(rem);
}
return rem;
}
public static void main(String[] args)
{
int result = 698239623; //input number
result = SumofDigits.sumofdigits(result);
System.out.println(result);
}
}
```

digit 9 has a secial property that when added to another digit, single digit some would be the other digit. When multiplied by other digit the resulting single sum woulb be 9.

using above observations, solution can be

if(num%9 == 0)

return 9;

else

return (num%9);

int Sum(int n){

- tito March 28, 2010int count = 0;

int r1 = n%10;

n = n/10;

while (n>9){

int r = n%10;

n = n/10;

r1 = r+r1;

if( r1 >10 ){

count++;

r1 = r1-10;

}

if(count >9){

count =1;

}

}

cout<<count<<endl;

r1 = r1+n;

if( r1 >10 ){

count++;

r1 = r1 - 10;

}

if(count >9){

count =1;

}

return (count+r1);

}