Problem
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
Hints:
- A naive implementation of the above process is trivial. Could you come up with other methods?
- What are all the possible results?
- How do they occur, periodically or randomly?
- You may find this Wikipedia article useful.
Example
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
Algorithm
给定一个非负整数num,将num 的每一位数字加起来。若加起来的和只有一位,则返回;若加起来的和有两位或两位以上的数字,则重复每一位数字求和过程,直到和只有一位数字。
首先看到题目即可写出O(n^2)的解法。若num大于10,则把每一位数字加起来;否则直接返回。
代码如下
//版本1,时间复杂度O(n^2)
class Solution {
public:
int addDigits(int num) {
if(num<10) return num;
int sum=0;
while(num/10>0){
sum=0;
while(num){
sum+=(num%10);
num/=10;
}
num=sum;
}
return sum;
}
};
然而题目中的Hint部分问是否存在O(1)的解法。要在O(1)时间内解决问题,一般都是存在某种规律。于是对结果进行枚举。枚举过程如下。
num | return | num | return |
---|---|---|---|
1 | 1 | 11 | 2 |
2 | 2 | 12 | 3 |
3 | 3 | 13 | 4 |
4 | 4 | 14 | 5 |
5 | 5 | 15 | 6 |
6 | 6 | 16 | 7 |
7 | 7 | 17 | 8 |
8 | 8 | 18 | 9 |
9 | 9 | 19 | 1 |
10 | 1 | 20 | 2 |
… | … | … | … |
可以发现num中每九个数,return就循环一次。于是可通过模9的方法直接得到返回值。
代码如下
//版本2,时间复杂度O(1)
class Solution {
public:
int addDigits(int num) {
if(num==0) return 0;
if(num%9==0) return 9;
else return num%9;
}
};