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.
java版1:
public class Solution {
public int addDigits(int num) {
return (num - 1) % 9 + 1;
}
}
java版2:
public class Solution {
public int addDigits(int num) {
return num == 0 ? 0 : (num % 9 == 0 ? 9 : num % 9);
}
}
python版:
class Solution(object):
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
add=lambda x:sum(int(i) for i in str(x))
s=add(num)
while 1:
if s<10:return s
else:s=add(s)