Leetcode 202. 快乐数 题解

本文分享了一道LeetCode上的简单题目“快乐数”的解题思路及代码实现。通过使用哈希表标记数字出现状态,避免了使用bool数组导致的超时问题,最终采用map实现快速查找,成功通过测试。

题目链接:https://leetcode-cn.com/problems/happy-number/
在这里插入图片描述
一道简单题,但是踩了十分钟的坑

哈希表标记出现与否,最开始用的bool数组,结果超时。之后看题解改成了map,就AC了。记录一下自闭时刻

代码如下:

class Solution {
public:
    int findsquare(int x) {
        int res = 0;
        while(x) {
            int t = x % 10;
            res += t * t;
            x /= 10;
        }
        return res;
    }
    
    bool isHappy(int n) {
        map<int, bool>cnt;
        while(1) {
            if(cnt[n]) {
                return false;
            } else if(n == 1) {
                return true;
            } else {
                cnt[n] = true;;
            }
            n = findsquare(n);
            cout << n << endl;
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值