[leetcode_258]Add Digits

O(1)的方法没有想出来,模拟的方法如下:
每次计算所有位数之和,直到该和小于10。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
    int addDigits(int num) {
        int sum = 0;
        while(num > 0)
        {
            sum += num % 10;
            num /= 10;
        }
        if (sum >= 10)
        {
            return addDigits(sum);
        }
        else
        {
            return sum;
        }
    }
};
Licensed under CC BY-NC-SA 4.0