题目如下:
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?
题目要求能不能在O(1)的时间里求出来,所以感觉应该是有某种规律可以直接推出结果的,所以从1开始列了数字然后算出结果,果真存在规律,从1到9然后又是从1到9,得到一下代码,通过。
class Solution {
public:
int addDigits(int num) {
return num==0?0:(num%9==0?9:num%9);
}
};
本文介绍了一种在O(1)时间内求解数字反复相加直至只剩一位数的方法。通过对数字1至9进行规律总结,得出简洁高效的算法实现。代码采用C++编写,适用于快速求解此类数学问题。
2633

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



