Oct 202012

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


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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>