Given an integer
num
, repeatedly add all its digits until the result has only one digit, and return it.
class Solution:
def addDigits(self, num):
while len(str(num)) > 1:
res = 0
length = len(str(num))
# 每一位数加上去
for i in range(length):
res += int(str(num)[i])
# 给 num 重新赋值
num = res
return num
class Solution:
def addDigits(self, num):
# 特例:0 --> 0
if num == 0:
return 0
# 能被 9 整除的数 --> 9
elif num % 9 == 0:
return 9
# 其余数字 --> 找最近一个能被 9 整除的数,计算差值 (mod 9)
else:
return num % 9