LeetCode 258 Add Digits(技巧 || 递归)
来源:互联网 发布:在线室内设计软件 编辑:程序博客网 时间:2024/06/07 03:23
Given a non-negative integer num
, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38
, the process is like: 3 + 8 = 11
, 1 + 1 = 2
. Since 2
has only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
题目大意:给出一个非负整数num,重复相加它的每一位直到最后只剩1位。
解题思路1:利用递归解决问题。
代码如下:
int addDigits(int num) { return num/10 ? addDigits(num%10+addDigits(num/10)) : num;}
解题思路2:利用公式dr(n) = 1 + ((n - 1) mod 9)可以在O(1)时间内求解,详解见digital root
代码如下:
int addDigits(int num) { return 1 + (num-1)%9;}
0 0
- LeetCode 258 Add Digits(技巧 || 递归)
- LeetCode(258) Add Digits
- leetcode 258: Add Digits
- 258Add Digits - LeetCode
- leetCode #258 Add Digits
- [LeetCode 258] Add Digits
- LeetCode(258)Add Digits
- leetcode-258-Add Digits
- [leetcode 258]Add Digits
- [Leetcode]#258 Add Digits
- LeetCode 258----Add Digits
- LeetCode 258 : Add Digits
- 【LeetCode】258 Add Digits
- Leetcode - 258 - Add Digits
- leetcode 258 :Add Digits
- leetcode 258--Add Digits
- leetcode 258 Add Digits
- Leetcode #258 Add Digits
- ConcurrentLinkedQueue读写
- 电源转换的两种类型电路(DC/DC,LDO)
- 2017 武大校赛 I: A simple math problem(矩阵快速幂)
- Linux粘滞位的设置
- 鼠标点击物体互换位置
- LeetCode 258 Add Digits(技巧 || 递归)
- IMweb训练营作业—-Todo List(vue)
- druid在spring boot中的使用
- Python时间,日期,时间戳之间转换
- linux—find指令常见用法示例
- 使用Windows自带的截图工具截取整个网页
- 【IMWeb训练营作业】todolist
- 51nod 1042
- os.path.splitext(“文件路径”)