码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Add Digits (a New question added)

时间:2015-08-17 10:00:19      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:

 

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;
    }
}

 

[LeetCode] Add Digits (a New question added)

标签:

原文地址:http://www.cnblogs.com/orangeme404/p/4735706.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!