题目来源【Leetcode】
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) {
while(num > 9){
int sum = 0;
while(num != 0){
sum += num%10;
num = num/10;
}
num = sum;
}
return num;
}
};
class Solution {
public:
int addDigits(int num) {
return 1 + (num - 1) % 9;
}
};
class Solution {
public:
int addDigits(int num) {
if (num <= 0) return 0;
return (num % 9) == 0 ? 9 : num % 9;
}
};
本文探讨了LeetCode上的一道经典题目:给定一个非负整数,反复累加其各个位上的数字直到结果仅剩一位数字,并提供了解决方案。一种直观的方法是循环累加直至结果为单个数字;另一种则是利用公式直接得出答案,避免循环。
173

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



