给定一个非负整数 num
,反复将各个位上的数字相加,直到结果为一位数。
示例:
复制代码
1
2
3输入:38
输出: 2 解释: 各位相加的过程为:3 + 8 = 11
,1 + 1 = 2
。 由于2
是一位数,所以返回 2。
思路 把数字转换为字符串再分割 ,然后转换为数字 循环相加知道值小于10
python3代码
复制代码
1
2
3
4
5
6
7
8
9class Solution: def addDigits(self, num: int) -> int: while num>=10: digit=list(map(int,str(num))) num=0 for i in range(len(digit)): num+=digit[i] return num
时间复杂度为O(1) 利用数学归纳法推导
复制代码
1
2
3
4
5
6class Solution: def addDigits(self, num: int) -> int: if (num%9==0) and (num!=0): return 9 else: return num%9
c++代码 时间复杂度为O(1)
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14class Solution { public: int addDigits(int num) { if(num>9) { num=num%9; if(num==0) { return 9; } } return num; } };
c++代码循环
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21class Solution { public: int addDigits(int num) { int sum =0; int temp=0; while(num>=10) { sum=0; while(num) { temp=num%10; sum+=temp; num/=10; } num=sum; } return num; } };
最后
以上就是想人陪石头最近收集整理的关于面试算法必考(3)leetcode的全部内容,更多相关面试算法必考(3)leetcode内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复