Leetcode202-Happy Number

本文介绍了一种用于判断一个数是否为快乐数的算法,并通过C++实现。快乐数是指通过不断将其各位数字的平方和相加,最终能得到1的正整数。文章详细解释了快乐数的概念,并给出了一种有效的方法来避免无限循环。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Leetcode202-Happy Number(Easy)

Write an algorithm to determine if a number is "happy".

A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.


题意:

happy数的定义如下:给定一个正整数,用其各位数的平方和取代该数,重复此操作直到该数等于1,或形成一个不为1的循环。其中,前者成为happy数。

例子:
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1


分析:

题目中已经给了提示,当能出现1时,即退出循环返回true;如出现了一个不为1的循环则返回false(如4, 16, 37, 58, 89, 145, 42, 20, 4, ...)。对happy number的详细描述见wiki百科:Happy Number。wiki还对Happy primes和Harshad number做了一些解释。为了快速确定是否发生非1的重复,使用unordered_set来记录已经出现过的数(我们并不关心数字的顺序,因此用hash效率更高)。


AC代码:

class Solution {
public:
    bool isHappy(int n) {
        int sum;
        unordered_set<int> check;
        check.insert(n);
        while (n != 1) {
        	sum = 0;
        	while (n) {
        		int t = n % 10;
        		n /= 10;
        		sum += t * t;
        	}
        	if (check.find(sum) != check.end())
        		return false;
        	check.insert(sum);
        	n = sum;
        }
        return true;
    }
};
如代码或分析有误,请批评指正,谢谢。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值