LeetCode 258:Add Digits

来源:互联网 发布:对位算法 编辑:程序博客网 时间:2024/05/23 00:10

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 = 111 + 1 = 2. Since 2 has only one digit, return it.

Follow up:

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

给定一个非负整数num,把它的每一位相加直至该数字只剩下一位。

例如,给定num=38,那么程序的运行过程为:3+8=11 1+1=2  因为2只有一位,因此返回2。

思考:你能把时间复杂度降到O(1)吗?



唔,自己做了好一会,一开始想的是直接从数字读,思路也挺简单的

class Solution {public:    int addDigits(int num) {        int sum=0,test=1;        if(num>=10)        {            while(num>=test)                test*=10;            while(test!=1)            {                int temp=num/(test/10);                sum+=temp;                num-=temp*(test/10);                test/=10;            }            if(sum<10)                return sum;            else addDigits(sum);        }        else return num;    }};

结果提示我超时了……

好吧,之后想的是把数字转换成字符串,不就能一个个读取了么

然而我并!不!会!数字转字符串。。。

我去百度还不行吗。。。

这里只转载了几个我认为比较常用到的

数字转字符串(这特么不是字符数组吗!)

char str[10];
int a=1234321;
sprintf(str,"%d",a);
--------------------
char str[10];
double a=123.321;
sprintf(str,"%.3lf",a);


字符串转数字(这特么不还是字符数组吗!)

string --> char *
   string str("OK");
   char * p = str.c_str();

char * -->string
   char *p = "OK";
   string str(p);


string->double
  double d=atof(s.c_str());

class Solution {public:    int addDigits(int num) {        char temp[15];        int sum=0;        sprintf(temp,"%d",num);        for(int i=0;temp[i]!='\0';i++)            sum+=(temp[i]-'0');        if(sum<10) return sum;        else addDigits(sum);    }};

最后看到follow up里问能不能把时间复杂度降到O(1)……点开几个Hint发现还是不会,于是还是老办法,百度之

以下转载自百度

另一个方法比较简单,可以举例说明一下。假设输入的数字是一个5位数字num,则num的各位分别为a、b、c、d、e。

有如下关系:num = a * 10000 + b * 1000 + c * 100 + d * 10 + e

即:num = (a + b + c + d + e) + (a * 9999 + b * 999 + c * 99 + d * 9)

因为 a * 9999 + b * 999 + c * 99 + d * 9 一定可以被9整除,因此num模除9的结果与 a + b + c + d + e 模除9的结果是一样的。

对数字 a + b + c + d + e 反复执行同类操作,最后的结果就是一个 1-9 的数字加上一串数字,最左边的数字是 1-9 之间的,右侧的数字永远都是可以被9整除的。

这道题最后的目标,就是不断将各位相加,相加到最后,当结果小于10时返回。因为最后结果在1-9之间,得到9之后将不会再对各位进行相加,因此不会出现结果为0的情况。因为 (x + y) % z = (x % z + y % z) % z,又因为 x % z % z = x % z,因此结果为 (num - 1) % 9 + 1,只模除9一次,并将模除后的结果加一返回。

class Solution {public:    int addDigits(int num) {        return (num - 1) % 9 + 1;    }};
好吧你赢了……


0 0
原创粉丝点击