LeetCode--258--各位相加*

时间:2022-09-16 17:00:56

问题描述:

给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数。

示例:

输入: 38
输出: 2
解释: 各位相加的过程为3 + 8 = 11, 1 + 1 = 2。 由于 2 是一位数,所以返回 2。

进阶:
你可以不使用循环或者递归,且在 O(1) 时间复杂度内解决这个问题吗?

方法1:

 class Solution(object):
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
num_list = []
if num // 10 == 0:
return num
num_list = self.jisuan(num,num_list)
while len(num_list) != 1:
res = 0
for i in num_list:
res += i
num_list = self.jisuan(res,[])
return res
def jisuan(self,num,num_list):#把[38]变成[3,8]
while num !=0:
g = num %10
num = num // 10
num_list.append(g)
return num_list

官方:amazing

 class Solution(object):
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
s = num % 9
return s if num==0 or s!=0 else 9

官方2:

 class Solution(object):
def addDigits(self, num):
a = str(num)
while len(a)-1:
a = sum([int(i) for i in str(a)])
a = str(a)
return int(a)

2018-09-22 16:56:58