Given a non-negative integer num
, repeatedly add all its digits until the result has only one digit.
Example:
Input: 38
Output: 2
Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
题目大意:
给出一个数按照这个数每一位相加得出新的结果,知道最终该结果为一个一位数。
解题思路:
模拟前几位的结果不难发现余数为1-9再到0的顺序9次一循环。
class Solution {
public:
int addDigits(int num) {
return num%9 == 0 ? num == 0 ? 0 : 9 : num % 9;
}
};