LeetCode258 Add Digits
来源:互联网 发布:数据库营销 编辑:程序博客网 时间:2024/06/05 12:21
不废话:
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?
- What are all the possible results?
- How do they occur, periodically or randomly?
- You may find this Wikipedia article useful.
class Solution {public: int addDigits(int num) { if(num==0){return 0;} return ((num-1)%9+1); }};
重点和技巧是上面的(num-1)%9+1
关于数论,有下面技巧:
ab=a*10+b;
ab%9=(a*9+a+b)%9=(a+b)%9
同理之下:
abc=a*100+b*10+c
abc=(a*99+b*9+a+b+c)%9=(a+b+c)%9
(自然数mod(9)后是0~8,而当需要输出1~9时,可以先mod(9)再整体+1)
0 0
- LeetCode258:Add Digits
- leetcode258 Add Digits
- leetcode258 Add Digits
- leetcode258: Add Digits
- [LeetCode258] Add Digits
- LeetCode258 Add Digits
- leetcode258 Add Digits java
- python--leetcode258. Add Digits
- LeetCode258——Add Digits
- leetcode258-Add Digits(非负整数各位相加)
- LeetCode258
- leetcode258
- Add Digits
- Add Digits
- Add Digits
- Add Digits
- Add Digits
- Add Digits
- 66 Plus One
- Intsant run深度分析
- bzoj 2836 树链剖分
- Python最简单的解决列表中只打印UNICODE而不是中文字符的方法
- 第23天(就业班) 文件上传及文件下载、邮件发送
- LeetCode258 Add Digits
- named-checkzone命令--Linux命令应用大词典729个命令解读
- smbpasswd命令--Linux命令应用大词典729个命令解读
- Lunix中三个重要时间和find命令
- PAT-B 1041. 考试座位号(15)
- Geoserver2.11矢量切片与OL3中的调用展示
- exit命令--Linux命令应用大词典729个命令解读
- reboot命令--Linux命令应用大词典729个命令解读
- [POJ3155]Hard Life(01分数规划)