您的位置:首页 > 其它

Add Digits

2015-09-15 06:57 288 查看
Add Digits

Difficulty: Easy

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?

Hint:

A naive implementation of the above process is trivial. Could you come up with other methods?

Hide Tags Math

Hide Similar Problems

最直接的思路:

num2用来统计num有多少位;

num1用来做除数。

eg.num为345,取百位,则num1得为1000(取余后,/(num1/10)即得百位数3)

int addDigits(int num) {
int num1,num2;
num1=1,num2=0;
int sum=0;
if(num/10 == 0)
return num;
while(num1 <= num){
num1 *= 10;
num2++;
}
while(num2--){
num %= num1;
num1 /= 10;
sum += num/num1;
}
addDigits(sum);
}


最终结果显示:Last executed input:

2032610959

Status: Time Limit Exceeded

显然该法虽直接,但运算效率太低。

于是我们对这些数做了下计算:

0-9,全部都各自返回本身(0-9)

10 -> 1

11 - > 2

……

19 - > 2

20 - > 2

21 - > 3

……

发现规律,最终结果的区间总落在[0,9]之间。

21%9余3,20%9余2,19%9余1,18%9余0,但实际上18对应结果为9.

所以应该总结为(num-1)%9+1;

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