问题:
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.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
大意:
给一个非负数,重复地加其中的数字知道最后只有一个数字。
比如说:
给出数字38,过程类似于:3+8=11,1+1=2.直到2只有一个数字了,就返回它。
继续:
你能不能不用任何循环、递归来在O(1)的时间复杂度中完成它?
思路一:
首先想到的就是循环,对于一个数字,循环将其除以10的余数加起来,直到其是个位数。加完一次后判断是不是只有一个数字,也就是是不是小于10,如果还大于,说明还有多个数字,那就再进行同样的操作。这个方法我自己测试倒是对的,不过leetcode总是说我超时,而且是在11这个数时就超时。。
代码一(c++):
class Solution {
public:
int addDigits(int num) {
int tempResult = num;
while (tempResult > 10) {
int tempNum = tempResult;
tempResult = 0;
for (; tempNum / 10 >= 1;) {
tempResult += tempNum % 10;
tempNum = tempNum / 10;
}
tempResult += tempNum;
}
return tempResult;
}
};
思路二:
既然题目里也鼓励我们继续思考不用循环的方式,那就一定是有规律可循。我们可以简单地列一下:
数字 | 结果 |
---|---|
0 | 0 |
1 | 1 |
2 | 2 |
3 | 3 |
4 | 4 |
5 | 5 |
6 | 6 |
7 | 7 |
8 | 8 |
9 | 9 |
10 | 1 |
11 | 2 |
12 | 3 |
13 | 4 |
14 | 5 |
15 | 6 |
16 | 7 |
17 | 8 |
18 | 9 |
19 | 1 |
20 | 2 |
21 | 3 |
就列这么多了,我们可以发现,结果除了第一个0以外,都在1~9之间循环。而且可以发现,其除以9的余数,为0时,对应的结果是9,而不为0时,余数等于对应的结果,那么代码就呼之欲出啦~
代码二(c++):
class Solution {
public:
int addDigits(int num) {
return num % 9 == 0 ? (num == 0 ? 0 : 9) : num % 9;
}
};
示例工程:https://github.com/Cloudox/AddDigits
合集:https://github.com/Cloudox/LeetCode-Record
版权所有:http://blog.youkuaiyun.com/cloudox_