LeetCode——Add Digits

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?

题目意思是重复地将一个数字每一位数字加起来得到一个新的数字直到得到一个一位数。

如果没有下面的提示O(1),恐怕我也就直接模拟去解决这道题了。

考虑到O(1)肯定不能用模拟来求解了,经过一番推导最终求出找出了规律,推导如下:

假设原来的数字为X,X可以表示为:

X=fn*Xn+fn-1*Xn-1+...+f1*x1 , Xn=pow(10,n-1);

对X进行一次操作后得到X‘:

X’=fn+fn-1+...f1

X-X':

X-X' = fn*(Xn - 1) + fn-1*(Xn-1 - 1) + ... f1*(X1 - 1)
     = fn*9···99 + fn-1*9···9 + ... f1*0
     = 9*( fn*1···11 + fn-1*1···1 + ... f2*1 + f1*0 )
     = 9*S (S is a non-negative integer)

 

每一次都比原来的数少了个9的倍数!

还要考虑一些特殊情况,最终程序:

 1 class Solution {
 2 public:
 3     int addDigits(int num) {
 4 /*
 5   X=fn*Xn+fn-1*Xn-1+...+f1*x1 , Xn=pow(10,n-1);
 6   Every operator make X=> X'=fn+fn-1+...f1
 7    X-X' =fn*(Xn - 1)+fn-1*(Xn-1 - 1)+...f1*(X1 - 1)
 8         =fn*9···99+fn-1*9···9+..f1*0
 9         =9*(fn*1···11+fn-1*1···1+...f2*1+f1*0)
10           =9*S (S is a non-negative integer)
11   => Everytime reduce a number of multiple 9
12  */
13         if(num==0) return 0;
14         int t=num%9;
15         return (t!=0)?t:9;
16     }
17 };

 

 

 

posted @ 2015-11-20 16:59  遥不可及,故叫梦想  阅读(838)  评论(0编辑  收藏  举报