Leetcode 258. Add Digits

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

For example:

Given num = 38, the process is like: 3 + 8 = 111 + 1 = 2. Since 2 has only one digit, return it.

Follow up:
Could you do it without any loop/recursion in O(1) runtime?

使用循环的解法如下:

 1 int addDigits(int num) {
 2     int sum = 0;
 3     while (num / 10)
 4     {
 5         while (num / 10)
 6         {
 7             sum += num % 10;
 8             num = num / 10;
 9         }
10         sum += num;
11         num = sum;
12         sum = 0;
13     }
14     sum += num;
15     return sum;
16 }

不使用循环的解法,参考了知乎,代码如下:

1 int addDigits(int num) 
2 {
3         if(num % 9 == 0 && num != 0)
4             return 9;
5         else
6             return num % 9;
7 }

 贴一张图片在这里:

原文地址:https://www.cnblogs.com/rainsoul/p/6688695.html