Leetcode 202. 快乐数 解题思路及C++实现

解题思路:

用递归的方法,出现1,就返回true,这里用了 unordered_map 来记录是否会出现循环。(也可以用unordered_set)

通过计算余数和商,来得到每个位置数字的平方和。具体看程序。

 

class Solution {
public:
    bool isHappy(int n) {
        if(n == 1) return true;
        unordered_map<int, int> mp;
        return whetherHappy(mp, n);
    }
    bool whetherHappy(unordered_map<int, int>& mp, int n){
        if(n == 1) return true;
        if(mp.find(n) != mp.end()) return false;
        else{
            mp[n] = 1;
            int tmp = 0;
            while(n > 0){
                int nn = n % 10;
                tmp += nn * nn;
                n = n / 10;
            }
            return whetherHappy(mp, tmp);
        }
    }
};

 

 

 


版权声明:本文为gjh13原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。