[leetcode] 258. Add Digits
来源:互联网 发布:井冈山大学网络平台 编辑:程序博客网 时间:2024/05/01 01:54
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.
这道题是求数根,题目难度为Easy。
这是一道纯数学知识的题目,不了解数根的同学可以看下wiki上的页面。数根求值公式为dr(n) = ((n-1) mod 9)+1。由于10^k ≡ 1^k≡ 1 mod 9,所以n ≡ dr(n) mod 9。这里编辑公式太麻烦,对证明过程还有疑问的同学可以看下文章结尾给出的知乎上的证明。具体代码:
class Solution {public: int addDigits(int num) { return (num - 1) % 9 + 1; }};知乎页面:http://www.zhihu.com/question/30972581
0 0
- 【LeetCode】258.Add Digits
- LeetCode 258. Add Digits
- LeetCode : 258. Add Digits
- leetCode 258. Add Digits
- LeetCode 258. Add Digits
- 258. Add 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
- 258.[LeetCode]Add Digits
- 【leetcode】258. Add Digits
- 在linux查看内存的大小
- 文本处理以及freetype的使用
- 计算listview上移距离,避免输入法遮挡
- Python文件处理
- Shell编程(1):变量
- [leetcode] 258. Add Digits
- GIT:git命令的使用分享下
- python3.5的安装 环境及notepad配置
- Map线程安全几种实现方法
- HDU_5791_Two(简单dp)
- 监督学习和无监督学习
- 矩阵转置的实现
- Python基础学习
- 为什么很多程序员不喜欢写单元测试?