原题链接: https://leetcode.com/problems/add-digits/
1. 题目介绍
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
给出一个非负数num,将num的每一位相加,得到一个新的数,再将这个新的数的每一位相加,重复这样的操作,直到得到的数只有个位时停下来。
返回这个个位数。
建议:不使用任何循环和递归来实现,时间复杂度为O(1)
Example:
Input: 38
Output: 2
Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2.
Since 2 has only one digit, return it.
2. 解题思路
2.1 循环或者递归
虽然说题目不提倡用循环或者递归的方法,但是我还是写了一下,简单看一看即可。
实现代码:循环
class Solution {
public int addDigits(int num) {
int ans = num;
while(ans>=10) {
int b = 0;
while(ans > 0) {
b += ans%10;
ans = ans/10;
}
ans = b;
}
return ans;
}
}
实现代码:递归
class Solution {
public int addDigits(int num) {
int ans = num;
while(ans>=10) {
ans = FindDigitsSum(ans);
}
return ans;
}
public int FindDigitsSum(int nums) {
int a = nums;
int b = 0;
while(a > 0) {
b += a%10;
a = a/10;
}
return b;
}
}
2.2 找规律
如果不用递归,不用循环,且时间复杂度为O(1)。这极有可能有一些数学规律。
于是打印一下0-30的所有结果:
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
22 4
23 5
24 6
25 7
26 8
27 9
28 1
29 2
30 3
可以发现,除了0以外,结果从1到9不停地在循环。于是答案就非常清晰了
实现代码
class Solution {
public int addDigits(int num) {
return (num%9 == 0 ? (num==0 ? 0 : 9) : num%9 );
}
}