leetcode 202 快乐数

简介: leetcode 202 快乐数

快乐数


17e49ec0a07d4a55ae20f8bc6e59a6b0.png

利用哈希表

不停循环计算每位数字的sum。当sum等于1的时候返回成功。

每一次的sum都存入哈希表中,当某一个sum第二次出现,为进入死循环。

因此发现sum在哈希表里第二次出现,返回失败。


#include <iostream>
#include<string>
#include<vector>
#include<set>
#include <unordered_set>
using namespace std;
class Solution {
public:
    bool isHappy(int n) {
        unordered_set<int> sum_set;
        int sum = 0;
        while (1)
        {
            if (n < 10) sum = n * n;
            else
            {
                while (n>=10)
                {
                    sum = sum + (n % 10) * (n % 10);
                    n = n / 10;
                }
                sum = sum + n * n;
            }
            if (sum == 1) return true;
            if (sum_set.find(sum) != sum_set.end()) return false;
            sum_set.insert(sum);
            cout << sum << endl;
            n = sum;
            sum = 0;
        }
    }
};
int main()
{
    Solution a;
    int n = 19;
    cout<< a.isHappy(n)<<endl;
  return 0;
}

二刷

class Solution {
public:
    bool isHappy(int n) {
        string num_s;
        int sum=0;
        vector<int> tmp;
        while( find(tmp.begin() , tmp.end(),n) == tmp.end())
        {
            cout<<n<<endl;
            tmp.push_back(n);
            num_s = to_string(n);
            for(int i=0 ; i<num_s.size();i++)
            {
                 sum += pow( (int)(num_s[i]-'0'),2 );
            }
            if(sum == 1 ) return true;
            else
            {
                n = sum;
                sum=0;
            } 
        }
        return false;
    }
};
相关文章
|
3天前
|
算法 容器
【LeetCode刷题】快乐数、盛水最多的容器
【LeetCode刷题】快乐数、盛水最多的容器
|
24天前
|
算法
【优选算法】——Leetcode——202—— 快乐数
【优选算法】——Leetcode——202—— 快乐数
【优选算法】——Leetcode——202—— 快乐数
|
1月前
|
算法
[leetcode] 快乐数 E
[leetcode] 快乐数 E
|
1月前
|
算法
LeetCode题:581. 最短无序连续子数组,242. 有效的字母异位词,202. 快乐数
LeetCode题:581. 最短无序连续子数组,242. 有效的字母异位词,202. 快乐数
32 0
|
1月前
|
算法 Java C++
「LeetCode」202. 快乐数
「LeetCode」202. 快乐数
21 0
|
1月前
|
算法 vr&ar 图形学
☆打卡算法☆LeetCode 202. 快乐数 算法解析
☆打卡算法☆LeetCode 202. 快乐数 算法解析
|
7月前
|
存储 算法 Serverless
代码随想录算法训练营第六天 | LeetCode 242.有效的字母异位词、349. 两个数组的交集、202. 快乐数、1. 两数之和
代码随想录算法训练营第六天 | LeetCode 242.有效的字母异位词、349. 两个数组的交集、202. 快乐数、1. 两数之和
51 0
代码随想录算法训练营第六天 | LeetCode 242.有效的字母异位词、349. 两个数组的交集、202. 快乐数、1. 两数之和
|
11月前
|
机器学习/深度学习
LeetCode存在重复元素快乐做题
LeetCode存在重复元素快乐做题
44 0
|
存储 人工智能 算法
【leetcode速通java版】05—— 快乐数、两数之和、四数相加II
【leetcode速通java版】05—— 快乐数、两数之和、四数相加II
|
算法
LeetCode每日1题--快乐数
LeetCode每日1题--快乐数
74 0