258. Add Digits
1. 问题描述
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.
Tags: Math
Similar Problems: (E) Happy Number
2. 解题思路
不用 循环 与 递归,毫无思路,从最简单情况开始分析:
- 对于一位数:0、1、2、3、4、5、6、7、8、9时,返回该数即可
- 对于两位数:10、11、12、13...,可发现规律,该返回 1 + (num-1)%9
- 对于三位数:100、101、102、103...,该规律同样适用,该返回 1 + (num-1)%9
3. 代码
1 class Solution { 2 public: 3 int addDigits(int num) 4 { 5 return 1 + (num-1)%9; 6 } 7 }
4. 反思
- 参考维基百科:https://en.wikipedia.org/wiki/Digital_root