首页 > 其他 > 详细

<LeetCode OJ> Add Digits【258】

时间:2015-12-28 10:35:07      阅读:251      评论:0      收藏:0      [点我收藏+]

258. Add Digits

My Submissions
Total Accepted: 54029 Total Submissions: 113401 Difficulty: Easy

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?

Hint:

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

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

Hide Tags
 Math
Show Similar Problems



























//思路首先:朴素的理想将数num的各个位提取出来,然后相加。如果只有一位就终止每一位的相加
//
class Solution {
public:
    int addDigits(int num) {
        int ans=0, cnt=2;
        while(cnt>1)
        {
            cnt=0;//判断当前这个数num的位数
            ans=0;
            //取出个位数相加
            while(num)
            {
                ans+=num%10;; //总是取出个位数
                num=num/10;
                cnt++;
            }
            if(cnt == 1)
                break;
            num =ans;//重新以和来取个位数相加
        }
        
        return ans;
    }
};



别人家的解法1:递归解法,思路清晰简单

class Solution {  
public:  
    int addDigits(int num) {  
        int sum=0;  
        while(num){  
            sum=sum+num%10;  
            num=num/10;  
        }  
        if(sum<10){  
            return sum;  
        }  
        else{  
            return addDigits(sum);  
        }  
    }  
};  



参考资源:

【1】网友,shensccs,博文地址,http://blog.csdn.net/shensccs/article/details/48469573

<LeetCode OJ> Add Digits【258】

原文:http://blog.csdn.net/ebowtang/article/details/50417277

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!