题目
Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.
Example 1:
Input: num = 38
Output: 2
Explanation: The process is
38 --> 3 + 8 --> 11
11 --> 1 + 1 --> 2
Since 2 has only one digit, return it.
Example 2:
Input: num = 0
Output: 0
Constraints:
0 <= num <= 2^31 - 1
Follow up: Could you do it without any loop/recursion in O(1) runtime?
递归解法
/*
* @lc app=leetcode.cn id=258 lang=java
*
* [258] 各位相加
*/
// @lc code=start
class Solution {
public int addDigits(int num) {
return (num < 10) ? num : addDigits(num / 10 + num % 10);
}
}
// @lc code=end
线性解法O(1)时间复杂度
public class Solution {
public int addDigits(int num) {
if (num == 0){
return 0;
}
if (num % 9 == 0){
return 9;
}
else {
return num % 9;
}
}
}
我将尝试解释其背后的数学原理:
首先,您应该了解:
10^k % 9 = 1
a*10^k % 9 = a % 9
然后让我们用一个例子来帮助解释。
说一个数字x = 23456
x = 2 * 10000 + 3 * 1000 + 4 * 100 + 5 * 10 + 6
2 * 10000%9 = 2%9
3 * 1000%9 = 3%9
4 * 100%9 = 4%9
5 * 10%9 = 5%9
然后x%9 =(2+ 3 + 4 + 5 + 6)%9
,请注意x = 2 * 10000 + 3 * 1000 + 4 * 100 + 5 * 10 + 6
所以我们有23456%9 =(2 + 3 + 4 + 5 + 6)%9