LeetCode
来源:互联网 发布:淘宝图片轮播怎么做 编辑:程序博客网 时间:2024/06/05 01:19
题目链接:258. Add Digits
题意:给你一个非负整数,将这个数的每一位拆开进行求和计算,直到只剩一位数为止。
例:num = 38
,先对num
进行拆分,3
和8
,求和为11
,再拆分1
和1
,求和为2
,2
就是最终的结果。
另:你能在不使用循环/递归的情况下,用O(1)的时间复杂度求出结果吗?
简单的解法,也就是使用循环求解的方法:
class Solution(object): def addDigits(self, num): if num == 0: return num while True: s = 0 while num > 0: s += num % 10 num //= 10 num = s if num < 10: break return num
原谅我对python的知识的了解的浅薄程度,只能写出这么难看的代码了,但是效果凑活吧。
接下来重点介绍一下,不用循环和递归的特殊解法。
这张图片来源于维基百科的一篇文章:Digital root。
关于算法的具体讲解过程,可以参看这篇文章。当然这个题目如果列出一些例子,也可以推测出这个规律。这里就不多展开了,我个人认为这种东西更偏向于基础知识点。
上代码:
class Solution(object): def addDigits(self, num): return (num - 1) % 9 + 1 if num != 0 else 0
one-liner
以上。
阅读全文
0 0
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- hdu_4847_kmp_水
- HTML5-简易Canvas绘图板
- 口胡【NOIP2011DAY1】选择客栈
- Python socket(TCP阻塞模式)基础程式
- java算法
- LeetCode
- c++数据结构:线性表实现之双链表
- 51nod 1323 完美平方
- 最长不下降子序列nlogn算法详解
- cookie和session
- 关于过载控制
- UML学---类图
- 算法笔记 //06_集合划分问题
- 简单线性回归及实现