<span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 30px; background-color: rgb(255, 255, 255);">For example:</span>
Given num = 38
, the process is like: 3 + 8 = 11
, 1 + 1 = 2
. Since 2
has only one digit, return it.
内容来源:https://leetcode.com/problems/add-digits/
最好想到的方法是递归演示,找到最后答案:class Solution {
public:
int addDigits(int num) {
int tmp = 0;
while (num > 9) {
while (num > 0) {
tmp += num % 10;
num /= 10;
}
num = tmp;
}
return num;
}
};
不过结果显示超时了。
第二种方法,看到提示,可以在O(1)的时间内完成,然后从10开始依次寻找规律,发现结果是(num - 1) % 9 + 1,
class Solution {
public:
int addDigits(int num) {
return (num - 1) % 9 + 1;
}
};
结果显示运行时间8ms AC。
然后看到C统计,有5ms AC的答案,所以好想知道怎么实现。