Add Digits
2015-09-15 06:57
288 查看
Add Digits
Difficulty: Easy
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?
Hint:
A naive implementation of the above process is trivial. Could you come up with other methods?
Hide Tags Math
Hide Similar Problems
最直接的思路:
num2用来统计num有多少位;
num1用来做除数。
eg.num为345,取百位,则num1得为1000(取余后,/(num1/10)即得百位数3)
最终结果显示:Last executed input:
2032610959
Status: Time Limit Exceeded
显然该法虽直接,但运算效率太低。
于是我们对这些数做了下计算:
0-9,全部都各自返回本身(0-9)
10 -> 1
11 - > 2
……
19 - > 2
20 - > 2
21 - > 3
……
发现规律,最终结果的区间总落在[0,9]之间。
21%9余3,20%9余2,19%9余1,18%9余0,但实际上18对应结果为9.
所以应该总结为(num-1)%9+1;
Difficulty: Easy
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?
Hint:
A naive implementation of the above process is trivial. Could you come up with other methods?
Hide Tags Math
Hide Similar Problems
最直接的思路:
num2用来统计num有多少位;
num1用来做除数。
eg.num为345,取百位,则num1得为1000(取余后,/(num1/10)即得百位数3)
int addDigits(int num) { int num1,num2; num1=1,num2=0; int sum=0; if(num/10 == 0) return num; while(num1 <= num){ num1 *= 10; num2++; } while(num2--){ num %= num1; num1 /= 10; sum += num/num1; } addDigits(sum); }
最终结果显示:Last executed input:
2032610959
Status: Time Limit Exceeded
显然该法虽直接,但运算效率太低。
于是我们对这些数做了下计算:
0-9,全部都各自返回本身(0-9)
10 -> 1
11 - > 2
……
19 - > 2
20 - > 2
21 - > 3
……
发现规律,最终结果的区间总落在[0,9]之间。
21%9余3,20%9余2,19%9余1,18%9余0,但实际上18对应结果为9.
所以应该总结为(num-1)%9+1;
int addDigits(int num) { return (num-1)%9+1; }
相关文章推荐
- Leetcode: Longest Substring Without Repeating Characters
- LeetCode Minimum Path Sum
- LeetCode Minimum Path Sum
- Linux常见问题汇总
- 蓝懿教育记录
- LeetCode (9): Palindrome Number
- OSChina 周二乱弹 —— 新一代开源尿床神器
- java虚拟机回收机制原理
- ZereneStacker 1.04 for Windows 焦点堆叠软件 简体中文 汉化
- ADT活動
- ASP.NET 5 Beta 7 版本
- 关于牛气轰轰的闭包
- Ugly Number II
- LeetCode Ugly Number II
- 插件开发技术说明(15)---文件自动分目录存储
- Lua的表(字典)
- LeetCode Ugly Number
- LeetCode Ugly Number
- Repeated DNA Sequences 解答
- Python二分查找详解