代码随想录-03-哈希表-04-快乐数

快乐数

题目

编写算法来判断数 n n n是不是快乐数

思路

  • g e t N u m getNum getNum函数,进行得到下一次计算结果;
  • 当计算结果不是在之前的循环中的数时,继续进行计算;否则,返回 f a l s e false false
  • 因为不要求有序,数字可能很大,且只用存储一个值,因此使用 unordered_set

具体代码

CPP

class Solution {
public:
    bool isHappy(int n) {
        int sum = 0;
        sum = getNum(n);
        set<int> res;
        while (sum != 1) {
            // 如果循环,那么不是快乐数
            if (res.find(sum) != res.end())
                return false;
            else {
                res.insert(sum);
                sum = getNum(sum);
            }
        }
        return true;
    }

    //如何实现sum函数
    int getNum(int n) {
        int sum = 0;
        while (n) {
            // 取个位上的平方
            sum += (n % 10) * (n % 10);
            // 右移一位
            n /= 10;
        }
        return sum;
    }

};
#include <iostream>
#include <unordered_set>
#include <cmath>
using namespace std;

class Solution
{
public:
    bool isHappy(int n)
    {
        unordered_set<int> hash;
        while (n != 1)
        {
            hash.insert(n);
            n = getNum(n);
            if (hash.find(n) != hash.end())
                return false;
        }
        return true;
    }

    int getNum(int n)
    {
        int res = 0;
        string s = to_string(n);
        for (int i = 0; i < s.size(); i++)
        {
            res += pow(s[i] - '0', 2);
        }
        return res;
    }
};

int main()
{
    Solution s;
    cout << s.isHappy(19) << endl;
    Solution s2;
    cout << s2.isHappy(2) << endl;
    Solution s3;
    cout << s3.isHappy(7) << endl;
    Solution s4;
    cout << s4.isHappy(1111111) << endl;
    system("pause");
    return 0;
}

Java


import java.util.HashSet;
import java.util.Set;

public class Main {

    public static void main(String[] res) {
        Solution n = new Solution();
        n.isHappy(19);
    }
}

class Solution {

    public boolean isHappy(int n) {
        if (n == 1) {
            return true;
        }
        Set<Integer> hash = new HashSet<>();
        hash.add(n);
        while (n != 1) {
            int next = getTransform(n);
            if (hash.contains(next)) {
                return false;
            } else {
                hash.add(next);
            }
            n = next;
        }
        return true;
    }

    public int getTransform(int n) {
        int res = 0;
        while (n != 0) {
            int cur = n % 10;
            res += cur * cur;
            n /= 10;
        }
        return res;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值