zoukankan      html  css  js  c++  java
  • 【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);
    }
  • 相关阅读:
    LeetCode刷题7——数字的补数
    Leetcode刷题6—不同路径
    Leetcode刷题5—最大子序和
    LeetCode刷题4——子集
    LeetCode刷题3——位1的个数
    LeetCode刷题2——颠倒二进制位
    小鸡啄米问题求解
    weavenet
    为系统守护进程预留计算资源
    PolicyRouting (ip rule)
  • 原文地址:https://www.cnblogs.com/wy1290939507/p/4519151.html
Copyright © 2011-2022 走看看