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)
{
//way-1
/*
while (num / 10 != 0)
{
int temp = 0;
while (num / 10)
{
temp += num % 10;
num /= 10;
}
temp += num;
num = temp;
}
return num;
*/
//way-2 找数据规律
if (num == 0)
return 0;
return (num-1) % 9 + 1;
}
};
本文介绍了一个数字累加算法,该算法能将一个非负整数的所有位数不断相加直至结果仅剩一位数。文中提供了两种实现方式:一种是通过循环进行逐位累加;另一种则是利用数学规律直接计算结果,后者能在常数时间内完成运算。
543

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



