Divisible by 3?

Give a method if a number is divisible by 3 without using the modulo operator.

Answer:

Sum the digits recursively until we are left with 3 or 6 or 9

bool IsDivisible(int num)
{
int sum_of_digits = 0;
if ( num < 10 )
{
if ( num == 3 || num == 6 || num == 9 )
return true;
else
return false;
}
while(num)
{
sum_of_digits += num % 10;
num = num / 10;
}
return IsDivisible(sum_of_digits);
}

No comments: