leetcode: 258. add digits

题目描述

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

Example:

1
2
3
4
Input: 38
Output: 2
Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2.
Since 2 has only one digit, return it.

写了几个数字之后,可以发现这个结果以9为一个循环,并且返回值为处以9后的余数。在整除的情况下,除了0返回0以外,其他都返回9(如9,18,27等)。

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
class  {
public:
int addDigits(int num) {
if (num == 0)
return 0;
int remain = num % 9;
if (remain == 0)
return 9;
else
return remain;
}
};