## Amazon Interview Question

Software Engineer in Testsint a=9999999,sum=10;

while (sum>9)

{

sum=0;

while(a>0)

{

sum=sum+a%10;

a=a/10;

}

a=sum;

}

```
//finds the sum of digits of a number
#include<cstdio>
int addDigits(int no) {
int negFlag=0;
int sum=0;
if(no<0) {
negFlag=1;
no=-no;
}
while(no>0) {
sum+=no%10;
no/=10;
}
return sum;
}
int main() {
printf("%d : %d ",567,addDigits(567));
printf("%d : %d ",5,addDigits(5));
printf("%d : %d ",0,addDigits(0));
printf("%d : %d ",-567,addDigits(-567));
}
```

int addnum(int a)

{int temp =a;

int res = 0;

char flag = 1;

do

{

res = res + temp % 10;

temp = temp/10;

if(temp == 0 && res <= 9)

{

flag=0;

}

if(temp == 0 && res > 9)

{

temp=res;

res=0;

}

printf("temp :%d res :%d \n\n",temp,res);

}while(flag);

printf( "final ans :%d \n\n",res);

return res;

}

```
// a recursive solution
unsigned int SumDigits(unsigned int number)
{
if (number >= 0 && number <= 9)
{
return number;
}
return (number % 10) + SumDigits(number / 10);
}
unsigned int SumDigitsTillSingleDigit(unsigned int number)
{
if (number >= 0 && number <= 9)
{
return number;
}
return SumDigitsTillSingleDigit(SumDigits(number));
}
```

int sum = 0;

int sumDigits( int n)

{

while (n>0){

sum = sum + n%10;

n/=10;

}

return sum;

}

This will not return sum as a single digit.

Ex. if n = 364, the above program would return 13; but, it should actually return 4.

Extending the above code,

int sum = 0;

void sumDigits(int n)

{

while (n>0){

sum = sum + n%10;

n/=10;

}

if(sum/10 > 0)

sumDigits(sum);

else

printf("%d", sum);

}

hi any one attended the test on that day........and gone thru some rounds of interview.....please post the questions here....

- Anonymous October 13, 2009Thanks,

Pavan