[LeetCode] Add Digits (a New question added)

 

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?

 

     貌似是前天还是大前天新加的一道题来着。

     这是一道很简单的题哈。直接用loop就可以解决。这是常规思维。接着下面分享一个非常取巧的算法。

     常规思维的代码如下。~(不要忘了-‘0’哦)

public class Solution {
    public int addDigits(int num) {
        String test=String.valueOf(num);
        while(test.length()>1){
            num=0;
            for(int i=0;i<test.length();i++){
                num=num+test.charAt(i)-'0';
            }
            test=String.valueOf(num);
        }
        return num;
    }
}

      还有一个非常巧妙的算法。 只要一行即可解决。代码如下。~

      这个算法的道理很简单,分别算算1-20的这20个数的add digits的结果,就可以找出规律了。

public class Solution {
    public int addDigits(int num) {
        return (num-1)%9+1;
    }
}

 

posted @ 2015-08-17 09:41  李小橘er  阅读(316)  评论(0)    收藏  举报