Add Digits

Posted on Updated on

Learn split the single digit for numbers from this problem and look for smart answers from the discussion.

while (num > 9)

sum += num % 10;

num = num / 10;

A good reference blog post:

while(num>9) num = num/10+num%10;
return num;

To achieve the challenge: Could you do it without any loop/recursion in O(1) runtime?

Try tens of trials to see the result iterates from 1 to 9. So a naive math way would be:

if(!num) return 0;

int a = num % 9;

if (a) return a;

else return 9;


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s