Add Digits

258.Add Digits

Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.

Example 1:

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

Example 2:

1
2
Input: num = 0
Output: 0

个人解答:

时间复杂度:O(log num)

空间复杂度:O(1)

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

进阶:

时间复杂度:O(1)

空间复杂度:O(1)

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