【LeetCode从零单刷】Add Digits
来源:互联网 发布:面纱3.0完美数据 编辑:程序博客网 时间:2024/05/22 14:06
题目:
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?
解答:
从头开始写,就会慢慢发现规律。是以 9 个数循环出现:1,2,3,……9,10,11,……对应的结果是1,2,3,……9,1,2,……
具体分析以及公式可见维基百科:Digital Root
class Solution {public: int addDigits(int num) { return (num - 1) % 9 + 1; }};
这里使用了一个小技巧:如果使用模9之后的余数来作为答案,那么9%9=0就是错误的。用 (num - 1)%9 + 1 来替代。以退为进
0 0
- 【LeetCode从零单刷】Add Digits
- [Leetcode从零开刷]258. Add Digits
- [leetcode][math] Add Digits
- [leetcode] Add Digits
- 【leetcode】Add Digits【java】
- Leetcode: Add Digits
- LeetCode Add Digits
- [LeetCode] Add Digits
- leetcode 258: Add Digits
- LeetCode题解:Add Digits
- leetcode: Add Digits
- 258Add Digits - LeetCode
- leetCode #258 Add Digits
- [LeetCode 258] Add Digits
- LeetCode: Add Digits
- LeetCode:Add Digits
- leetcode--add digits
- leetcode Add Digits
- Error:A problem occurred configuring project ':app'. > failed to find Build
- 抽象类和接口的区别
- Helloworld
- centos 双网卡配置
- 你才20多岁,为什么总怕来不及
- 【LeetCode从零单刷】Add Digits
- 64 Minimum Path Sum
- stringstream的用法
- sql语句优化小技巧
- linux帮助命令与压缩-3
- centos 局域网通过一台计算机桥接上网
- GridView分页
- HelloWorld
- centos 局域网时间同步(NTP)