码迷,mamicode.com
首页 > 移动开发 > 详细

【leetcode】happy number--easy

时间:2015-05-21 12:34:56      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

如果一个数的每个位的整数的平方和等于1,则为happy number

Example: 19 is a happy number

  • 12 + 92 = 82
  • 82 + 22 = 68
  • 62 + 82 = 100
  • 12 + 02 + 02 = 1
#include<iostream>
#include<vector>
#include <math.h>
using namespace std;

class Solution {
public:
    bool isHappy(int n) {
        temp.insert(temp.begin(),n);   //把当前值加入到历史路径中
        int r=addsquare(n,0);
        if(r==1)   //如果已经达到了happy number的条件
            return true;
        else
        {
            for(vector<int>::iterator it=temp.begin();it!=temp.end();it++)    //如果没有达到happy number的条件,那么比较r值和历史值是否重合
            {
                if(r==*it)  
                    return false;   //如果和历史值重合了,则不是happy number
            }
            isHappy(r);   //如果和历史结果没有重合,则继续往后计算
        }    
    }
private:
    vector<int> temp;
    int addsquare(int n,int r){
            //char str[11];
            //itoa(n,str,10);    //数字转换为字符串,10代表10进制
            //int r=0;
            //char *ptr=str;
            //while(*ptr!=‘\0‘)
            //{
            //    r+=(*ptr-‘0‘)*(*ptr-‘0‘);
            //    ptr++;
            //}
            //return r;
        int tmp=n%10;
        r+=tmp*tmp;
        n=(n-tmp)/10;
        if(n==0)
            return r;
        else
            addsquare(n,r);
        }
};

void main()
{
    Solution S;
    int n;
    cin>>n;
    cout<<S.isHappy(n);
}

 

【leetcode】happy number--easy

标签:

原文地址:http://www.cnblogs.com/wy1290939507/p/4519151.html

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