19.Happy Number-Leetcode

Write an algorithm to determine if a number is “happy”.

A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.

Example: 19 is a happy number

12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
基本思路:
按照生成的思路写出相应代码,重点是考虑到循环何时跳出,此题若在
生成中间数的过程出现了重复,那一定会无休止的循环下去,便不是happy number,故用一个map来保存状态,暂未发现直接判断的方法

#define IMAX numeric_limits<int>::max()
class Solution {
public:
    bool isHappy(int n) {
        if(n<=0)return false;
        map<int,int> vis;
        //int num = pow(10,9);
        while(n!=1)
        {
           // num++;
            //if(num==IMAX)break;
            if(vis.count(n))return false;//出现重复的中间数
            vis[n]=1;
            vector<int> vs;
            while(n)
            {
                vs.push_back(n%10);
                n=n/10;
            }
            n=0;
            for(int i=0;i<vs.size();++i)n=n+vs[i]*vs[i];
        }
        return true;
    }
};
原文地址:https://www.cnblogs.com/freeopen/p/5482982.html