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.
int addDigits(int num) {
if(num<10)
return num;
if(num%9==0)
return 9;
else
return num%9;
}
另一种方式是直接应用公式
a的数根b = ( a - 1) % 9 + 1
本文介绍了一种快速求解数字根的方法,通过数学公式而非循环或递归的方式实现了对任意非负整数数字根的计算。文章给出了两种实现方案:一种是通过简单的条件判断返回数字根;另一种则是直接应用数学公式。
552

被折叠的 条评论
为什么被折叠?



