题目描述:
给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数。
示例:
输入: 38
输出: 2
解释: 各位相加的过程为:3 + 8 = 11, 1 + 1 = 2。 由于 2 是一位数,所以返回 2。
进阶:
你可以不使用循环或者递归,且在 O(1) 时间复杂度内解决这个问题吗?
思路:
本题要找到[规律](http://www.sjsu.edu/faculty/watkins/Digitsum00.htm).
当n % 9 == 0时, 各位相加结果为9.
当 n % 9 !=0 时,各位相加结果为n%9.
当 n == 0时, 结果为0.
n 和 n%9
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
6 6 6
7 7 7
8 8 8
9 9 0
10 1 1
11 2 2
12 3 3
13 4 4
14 5 5
15 6 6
16 7 7
17 8 8
18 9 0
Java解法:
class Solution {
public int addDigits(int num) {
if(num == 0) return 0;
if (num % 9 ==0)
{
return 9;
}else{
return num % 9;
}
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers
网友评论