首页 > 移动平台 > 详细

Happy Number

时间:2015-07-07 11:08:32      阅读:146      评论:0      收藏:0      [点我收藏+]

解决问题的思路:
技术分享
第一步:从上图中,我们可以发现:在闭区间[1,13]内的所有数经过次数有限的迭代后,它们将会变成1或者4,而1是happy number,4不是happy number。进而可以判断出闭区间[1,13]内的所有数的happy性。

第二步:下面我做了一个大胆的假设,所有的正数经过可接受的有限次迭代后都将变成1或者4。由于在数学上给出证明所需的时间远远大于用程序验证,所以暂且不进行数学证明,直接进行在线编程。结果正确。

代码如下:

class Solution {
public:
    bool isHappy(int n) {
        int quotient, remainder;
        vector<int> digitalArr;

        quotient = n;
        int i = 1;
        while(true) {

            digitalArr.clear();
            for(; quotient != 0; ) {
                remainder = quotient % 10;
                quotient = quotient / 10;
                if(remainder != 0)
                digitalArr.push_back(remainder);
            }

            quotient = 0;
            for(vector<int>::iterator iter = digitalArr.begin(); iter != digitalArr.end(); iter++) {
                    quotient = quotient + (*iter) * (*iter);
            }

            if(quotient == 1 || quotient == 4)
                break;
        }
        if(quotient == 1)
            return true;
        else
            return false;
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

Happy Number

原文:http://blog.csdn.net/guanzhongshan/article/details/46785379

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