您的位置:首页 > 其它

258. Add Digits

2016-05-13 14:13 239 查看

258. Add Digits

Description:

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

Could you do it without any loop/recursion in O(1) runtime?

Example:

For example:

Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.

Hint:

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

2. What are all the possible results?

Link:

https://leetcode.com/problems/add-digits/

Analysis:

1. 针对这个题目,第一反应是使用递归。但是题目已经说明时间复杂度为O(1)。所以就要换个思路了。碰到这种问题还是可以先多尝试几个数,随便试一下。

2. 这道题其实还是不太好想的(反正我是没想出来,看网上的答案,哈哈),需要用到一个技巧:

A.首先,假设num1为一五位数,

则num1=(a+b+c+d+e)+(a*9999+b*999+c*99+d*9),且num1%9=(a+b+c+d+e)%9;

B.而(a+b+c+d+e)可能仍然大于9,令其等于num2;

即(a+b+c+d+e)=num2=(f+g)+(f*9),有num1%9=(f+g)%9;

C.这里假设num3=(f+g),值小于等于9(这样总会化简到1~9之间的数),则num1%9=num3%9,而num3正是num1各位数累加的结果,也就是我们想要得到的值

D.但是注意一点,我们通过num1%9只能得到num3%9而非num3,所以我们还需要最后一步处理(注意最后一列):

num3%9:123456780
num3:123456789
对于这一过程,最直观的方法就是用if语句判断一下,当然有些人用了更简便的一条语句:(num-1) % 9 + 1。都可以吧。

Source Code(C++):

#include <iostream>
using namespace std;

class Solution {
public:
int addDigits(int num) {
if (num==0) {
return 0;
}
else {
// return (num-1)%9+1;
int k = num%9;
if (k==0){
return 9;
}
else{
return k;
}
}
}
};

int main() {
Solution s;
cout << s.addDigits(38);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: