问题描述
问题链接:https://leetcode.com/problems/add-digits/#/description
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?
Hint:
- A naive implementation of the above process is trivial. Could you come up with other methods?
- What are all the possible results?
- How do they occur, periodically or randomly?
- You may find this Wikipedia article useful.
我的代码
思路是看了wiki的文章才有的。代码如下:
public class Solution {
public int addDigits(int num) {
/*
思路:看了https://en.wikipedia.org/wiki/Digital_root的解释
答案就是如果digit_root=9,那么这个数就是9的倍数,如果digit_root<9,那就是这个数-digit_root是9的倍数
所以取模计算即可得到结果,不过注意对<=9和9的倍数的数的处理。
*/
return num <= 9?num:(num % 9 == 0?9:num%9);
}
}
打败了24.54%的Java代码。来看看讨论区。
讨论区
Accepted C++ O(1)-time O(1)-space 1-Line Solution with Detail Explanations
这个厉害了,套路深啊。
class Solution {
public:
int addDigits(int num) {
return 1 + (num - 1) % 9;
}
};