202. 快乐数

202. 快乐数


题目链接:202. 快乐数

代码如下:

//思路:如果陷入循环,那么这个过程中肯定有已经出现过的数,把这当成打破循环的条件
class Solution {
public:
    bool isHappy(int n) {
        unordered_set<int> arr;

        while(1)
        {
            int sum=0,temp=1;
            while(n!=0)
            {
                temp=n%10;
                sum+=temp*temp;
                n/=10;
            }

            if(sum==1)//找到了就返回
                return true;

            if(arr.find(sum)!=arr.end())
                return false;

            arr.insert(sum);//出现过就插入
            n=sum;
        }
        return false;
    }
};

你可能感兴趣的:(leetcode,c++)