【leetcode】happy number--easy

如果一个数的每个位的整数的平方和等于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!='')
            //{
            //    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);
}
原文地址:https://www.cnblogs.com/wy1290939507/p/4519151.html