Given a non-negative integernum
, repeatedly add all its digits until the result has only one digit.
For example:
Givennum = 38
, the process is like:3 + 8 = 11
,1 + 1 = 2
. Since2
has only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
题目让求各个数位的和,直到和小于10为止,
方法一
直观的想法就是直接相加,先想一下如何求各数位的和
while(num != 0)
{
tmp += num % 10;
num /= 10;
}
下面是完整代码
class Solution {
public int addDigits(int num) {
while(num / 10 > 0)
{ int sum = 0; ////注意定义变量的位置
while(num != 0)
{
sum += num % 10;
num /= 10;
}
num = sum;
}
return num;
}
}
方法二
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
这20个数的数根有循环,且循环周期为9,循环的计算公式为(n-1)%cycle + 1,所以该题目i可以使用一行代码搞定
class Solution {
public:
int addDigits(int num) {
return (num - 1) % 9 + 1; //周期第一位为1,若为2 则 + 2
}
};
<wiz_tmp_tag id="wiz-table-range-border" contenteditable="false" style="display: none;">