leetcode 258_adddigits

Description

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 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.

Solution

有一种解法是利用循环完成:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int (int num) {
while(num/10 >= 1){
int sum = 0;
int n = num;
while(n > 0){
sum += n%10;
n /= 10;
}
num = sum;
}
return num;
}
};

另一种解法,利用mod,小学的时候学过判断一个数能不能被9整除,直接将各位的数相加判断能不能被9整除,这个与本题有异曲同工之处,所以可以利用mod9的余数来表示。因为各个数相加不可能等于0,所以可以如下:

1
2
3
4
5
6
class Solution {
public:
int (int num) {
return 1 + (num - 1) % 9;
}
};