您的位置:首页 > 其它

LeetCode *** 258. Add Digits

2016-04-01 11:08 253 查看
题目:

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),那么可以进行如下分析:

数字结果
00
11
22
33
44
55
66
77
88
99
101
112
123
134
145
156
167
178
189
191
202
213
224
235
246
257
268
279
281
292
那么代码如下:

int addDigits(int num) {
if(num==0)return 0;
if(num%9)return num%9;
else return 9;
}


还有一个代码更加简单,如下:

int addDigits(int num) {
return (num - 1) % 9 + 1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: