码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode--258--各位相加*

时间:2018-09-22 23:22:32      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:时间复杂度   type   lse   ddd   append   +=   返回   相加   res   

问题描述:

 

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

示例:

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

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

方法1:

 1 class Solution(object):
 2     def addDigits(self, num):
 3         """
 4         :type num: int
 5         :rtype: int
 6         """
 7         num_list = []
 8         if num // 10 == 0:
 9             return num
10         num_list = self.jisuan(num,num_list)
11         while len(num_list) != 1:
12             res = 0
13             for i in num_list:
14                 res += i
15             num_list = self.jisuan(res,[])
16         return res       
17     def jisuan(self,num,num_list):#把[38]变成[3,8]
18         while num !=0:
19             g = num %10
20             num = num // 10
21             num_list.append(g)
22         return num_list

官方:amazing

1 class Solution(object):
2     def addDigits(self, num):
3         """
4         :type num: int
5         :rtype: int
6         """
7         s = num % 9
8         return s if num==0 or s!=0 else 9

官方2:

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

2018-09-22 16:56:58

LeetCode--258--各位相加*

标签:时间复杂度   type   lse   ddd   append   +=   返回   相加   res   

原文地址:https://www.cnblogs.com/NPC-assange/p/9690505.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!