leetcode 202 快乐数

 

 

class Solution {
public:
    bool isHappy(int n) {
        unordered_map<int,bool> m;
        while(n!=1){
            m[n]=true;
            int sum=0,a;
            while(n){
                a=n%10;
                sum+=a*a;
                n/=10;
            }
            n=sum;
            if(m[n]) return false;
        }
        return true;
    }
};

使用hash set

/**
使用一个hash set 或者hashmap来记录已经出现的数字,如果出现的数是出现过的(有循环)return false;如果最终返回1,break; return true;
**/

class Solution {
public:
    bool isHappy(int n) {
        unordered_set<int> s;
        while(n!=1){
            s.insert(n);
            int tmp=0;
            while(n!=0){
                int k=n%10;
                tmp+=k*k;
                n=n/10;
            }
            n=tmp;
            if(s.count(n)) return false;
        }
        return true;
    }
};/**
使用一个hash set 或者hashmap来记录已经出现的数字,如果出现的数是出现过的(有循环)return false;如果最终返回1,break; return true;
**/

class Solution {
public:
    bool isHappy(int n) {
        unordered_set<int> s;
        while(n!=1){
            s.insert(n);
            int tmp=0;
            while(n!=0){
                int k=n%10;
                tmp+=k*k;
                n=n/10;
            }
            n=tmp;
            if(s.count(n)) return false;
        }
        return true;
    }
};

 

posted @ 2019-04-15 10:30  Joel_Wang  阅读(178)  评论(0编辑  收藏  举报