[LeetCode 258] Add Digits
来源:互联网 发布:触摸屏软件下载 编辑:程序博客网 时间:2024/06/05 03:37
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
. Since2
has only one digit, return it.Follow up:
Could you do it without any loop/recursion in O(1) runtime?
Solution:
1) while loop until the number is no longer bigger than 9.
public int addDigitsLoop(int num) { if(num < 10) { return num; } while(num > 9) { String str = "" + num; int addition = 0; for (int i = 0; i < str.length(); i++) { String temp = "" + str.charAt(i); addition += Integer.parseInt(temp); } num = addition; } return num;}
2) recursion
public int addDigits(int num) { if(num < 10) { return num; } String str = "" + num; int addition = 0; for(int i=0; i<str.length();i++) { String temp = "" + str.charAt(i); addition += Integer.parseInt(temp); } if (addition > 9) { addition = addDigits(addition); // remember to assign the value to a variable } return addition;}
注:这些方法都很 naive,还要把num 转换成字符串,这样过于繁琐,效率太低。 明天考虑考虑不用字符串的方法。
0 0
- 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
- LeetCode 258:Add Digits
- LeetCode 258:Add Digits
- git 代码库回滚
- Android版本列表
- Notepad++编译C语言代码的配置过程
- 用strace工具跟踪系统调用
- 远程调用Spark平台中的程序
- [LeetCode 258] Add Digits
- 拓扑排序+优先队列
- C语言open()函数:打开文件函数
- Android 时间戳简单转化
- C++ 贪吃蛇穿墙与自定义地图
- WebView自适应
- JavaScript组成
- Activity管理和应用程序的退出(推荐使用stack)
- shell中for循环总结