leetcode 202. 快乐数 c++

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/glw0223/article/details/89136939

202. 快乐数

题目

编写一个算法来判断一个数是不是“快乐数”。

一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到 1。如果可以变为 1,那么这个数就是快乐数。

示例:

输入: 19
输出: true
解释: 
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

分析

  • map的使用
  • 还有hash_map、unordered_map需要研究和分析
class Solution {
public:
    int func(int n){
        int temp = 0;
        while(n>0){
            int remainder = n%10; //余数
            temp += remainder*remainder;
            n/=10;
        }
        return temp;
    }
    bool isHappy(int n) {
        map<int,int> myMap;//map的实现是红黑树
        myMap[n] = 0;
        bool result = true;
        while(n!=1){
            n = func(n);
            if(myMap.find(n)!=myMap.end()){
                result = false;
                break;//找到的相同数,说明无限循环
            }
            myMap[n]=0;
        }
        return result;
    }
};

猜你喜欢

转载自blog.csdn.net/glw0223/article/details/89136939