leetcode解题报告258——Add Digits
来源:互联网 发布:精算师 知乎 编辑:程序博客网 时间:2024/06/04 20:14
题目:
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?
思路:
用递归方法,代码如下。
但是题目说了不建议用递归。
public int addDigits(int num) { if (num < 10) { return num; } int res = 0; while (num > 0) { res += num % 10; num = num / 10; } return addDigits(res); }
找规律(第一行为输入数字,第二行为数字的叠加和)
规律:除了第一个数字0外,呈现从1~9循环的规律。
代码:
public int addDigits4(int num) { if (num == 0) { return 0; } int res = num % 9; if (res == 0) { return 9; } else { return res; }}
0 0
- leetcode解题报告258——Add Digits
- LeetCode-Add Digits-解题报告
- 【LeetCode解题报告】Add Digits
- 【LeetCode】 Add Digits 解题报告
- [leetcode] 258. Add Digits 解题报告
- LeetCode 258.Add Digits 解题报告
- leetcode解题报告258. Add Digits
- [Leetcode] 258. Add Digits 解题报告
- LeetCode[258]——Add Digits
- LeetCode --- 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
- 【Ajax技术】解决XHR与图片缓存问题
- substr()函数截取字符串
- /proc/stat
- java开发中加载配置文件
- java实现全排列
- leetcode解题报告258——Add Digits
- position:fixed失效的问题
- EBS TimeZone问题
- glsurfaceview 使用skia
- HDU1081——动态规划简单题
- mysql5.6.16绿色版配置、运行
- “IE浏览器不支持在css文件中设定的dialog宽度”解决方法
- could not create java virtual machine
- Android 组件类继承关系结构图