LeetCode 258. Add Digits 题解(C++)
题目描述
- Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
示例
- Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
限制条件
- Could you do it without any loop/recursion in O(1) runtime?
思路
代码
我的代码
class Solution
{
public:
int addDigits(int num)
{
while (num / 10 != 0)
{
num = (num / 10) + (num % 10);
}
return num;
}
};
使用数根公式的代码
class Solution
{
public:
int addDigits(int num)
{
return 1 + (num - 1) % 9;
}
};