问题描述
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?
思路分析
将一个非零整数的所有位加和起来,知道产生一个一位数字。
当result大于零,将result各位模10再除10直到所有位都加和起来了,两个循环嵌套。
代码
class Solution {
public:
int addDigits(int num) {
int result = num, n = num;
while(result >= 10){
n = result;
result = 0;
while(n != 0){
result += n % 10;
n = n / 10;
}
}
return result;
}
};
时间复杂度:不知
空间复杂度:
O(1)
反思
关于follow up,如何不使用遍历来解决这个问题。 O(1) 时间复杂度。
成为一个数学问题,求数根wiki链接。
简单来说一个数和每一位之后加和起来的数模9同余。所以直接模9就可以,再用(num-1)% 9 + 1避免9的倍数的情况即可。
class Solution {
public:
int addDigits(int num) {
return (num - 1) % 9 + 1;
}
};