comma operator
October 19, 2012
Rotating a linked list around pivot
October 20, 2012

Sum the digits of a number in single statement

Write a single statement (simple or compound) which can compute sum of digits of an unsigned int.

Solution:

You should not expect such questions in companies like Microsoft, Adobe, Amazon or Google.. But some companies are fascinated with tricky questions in the interview. Anyways, the code can be as below:

for(sum=0; n > 0; (sum+=n%10, n/=10) );

Here comma is acting as a operator.

Same thing can be done recursively also:

int sumDigits(unsigned int n)
{
  return (n == 0) ? 0 : ( n%10 + sumDigits(n/10) ) ;
}

Leave a Reply

Your email address will not be published. Required fields are marked *