Add Digits
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?
给定一个非负整数num,反复添加的所有数字直到结果只有一个数字。
num、结果、num%9
0 0 0
1 1 1
2 2 2
...
9 9 0
10 1 1
11 2 2
12 3 3
13 4 4
...
18 9 0
19 1 1
20 2 2
...
99 9 0
100 1 1
...
999 9 0
1000 1 1
=>算法:
public class Solution {
public int AddDigits(int num)
{
return num == 0 ? 0 : num%9 == 0 ? 9 : num%9;
}
}
看着比较乱,再优化一下:
public class Solution {
public int AddDigits(int num)
{
int[] result = {9, 1, 2, 3, 4, 5, 6, 7, 8};
return num > 0 ? result[num%9] : 0;
}
}