【LeetCode】202 Happy Number

本文介绍了一种算法用于判断一个正整数是否为快乐数,快乐数定义为通过将数字替换为其各位数字的平方和并重复此过程直到得到1或进入循环的数。文中提供了两种实现方法,并解释了使用HashSet解决死循环问题的原理。

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

<span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; background-color: rgb(255, 255, 255);">Write an algorithm to determine if a number is "happy".</span>

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.

Example: 19 is a happy number

  • 12 + 92 = 82
  • 82 + 22 = 68
  • 62 + 82 = 100
  • 12 + 02 + 02 = 1
法1:(Runtime: 5 ms

public class Solution {
    public boolean isHappy(int num) {
        if (num == 0 || num == 1) {
			return true;
		}
		Set<Integer> set = new HashSet<Integer>();
		set.add(num);
		while (true) {
			int sum = 0;
			while(num != 0){
				int temp = num % 10;
				sum += temp * temp;
				num = num / 10;
			}
			if(sum == 1){
				return true;
			}
			if (!set.add(sum)) {
				return false;
			}
			num = sum;
		}
    }
}


法2:(Runtime: 9 ms

public class Solution {
    public boolean isHappy(int num) {
        if (num == 0) {
			return true;
		}
		Set<Integer> set = new HashSet<Integer>();
		set.add(num);
		String s = num + "";
		while (Integer.parseInt(s) != 1) {
			int sum = 0;
			for (int i = 0; i < s.length(); i++) {
				int temp = Integer.parseInt(s.charAt(i) + "");
				sum += temp * temp;
			}
			if(!set.add(sum)){
				return false;
			}
			s = sum + "";
		}
		return true;
    }
}

刚开始构思时,迟迟想不到用什么办法来中断计算死循环,在网上搜索了一些资料以后,发现可以用HashSet来解决死循环问题,因为Set是不重复集合,只要发现往其中添加的数是已存在的,即可判断循环计算回到死循环节点,此时即可跳出循环。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值