题目
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
解法一
我寻思我就遍历一遍,已经算是很精简了,谁知有更简单的。
class Solution:
def addDigits(self, num: int) -> int:
result=0
for s in str(num):
result+=int(s)
if(result>9):
result=result//10+result%10
return result
解法二
这个推导过程我挣扎了两天,实在是看不进心里去,给自己放个水~~后面如果看懂了再来补
class Solution {
public:
int addDigits(int num) {
return 1 + (num - 1) % 9;
}
};