您的位置:首页 > 编程语言 > Go语言

LeetCode Algorithms #258 <Add Digits>

2015-10-07 08:02 405 查看
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?

思路:

非零整数,每增加1,

1.如果个位是0~8,则是个位数加1,十位百位等都不会改变。

则会导致各个数位加和的结果加1。

2.如果个位数是9,个位加1变0,十位加1。

则会导致各个数位加和的结果减9加1。

这个规律在每一次加和这个数的各个数位时都有效,所以最终一定是一个以9为最小周期变化的结果。

验证代码:

#include <iostream>

int main(int argc, const char * argv[]) {
std::cout << "GoodMorning, Neuwyt!\n";
for(int idx = 1; idx < 100; idx++)
{
int tempResult = 0;
tempResult = idx%10 + idx/10;
if(tempResult/10)
{
tempResult = tempResult%10 + tempResult/10;
}
printf("%d, ", tempResult);
}
return 0;
}


输出结果:

GoodMorning, Neuwyt!
1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9,
发现规律。

综上,解:

class Solution {
public:
int addDigits(int num) {
int result = 0;
result = 1 + (num-1)%9;
return result;
}
};
另:使用临时变量会导致解题的速度慢上几毫秒,但实际工作中更利于维护和阅读,本人工作的项目一般不太看重效率,也不是acm出身的,因此养成了这样写代码的习惯。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: