258. Add Digits
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?
class Solution {
public:
int addDigits(int num) {
return num - (num - 1) / 9 * 9;
}
};
本文介绍了一个高效算法,能够在O(1)时间内解决加位数问题:对于任意非负整数,通过不断将各位数字相加直至只剩一位数的过程。文章给出了一种不使用循环或递归的方法,只需一次计算即可得出结果。
546

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



