[LeetCode] 202. Happy Number

原题链接: https://leetcode.com/problems/happy-number/

1. 题目介绍

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数字。
happy数字的定义是把每一位的平方相加,得到一个新的数,然后再重复这个过程,最终如果能得到1,那么这个数字就是happy数字。如果是无限的循环,这个数字就不是happy数字。

Example:
在这里插入图片描述

2. 解题思路

2.1 投机取巧的方法(不建议)

这个题难点在于判断循环何时结束,当循环达到一定次数时,就直接判断它无法结束。虽然能够过题,但是这个方法的结果仍然有可能是错误的,有风险,不建议使用。
success但是有可能出错的代码

class Solution {
    public boolean isHappy(int n) {
		
		int a = 1;
		for(int i = n;;) {
			i = Count(i);
			a++;
			if(i ==1) {
				return true;
			}
			if(a >1000000) {
				return false;
			}
		}
        
    }
	public int Count(int num) {
        
		int ans = num;
		int b =0;
	        while(ans > 0) {
	        	b += (ans%10) * (ans%10);
	        	ans = ans/10;
	        }
	        ans = b;
		return ans;
    }
}

2.2 找规律

遇到这样的问题,如果一时不知道怎么解决,可以试着打印出前面几个数的结果,然后在其中寻找规律。
比如先把 2 的前30个运算步骤打印出来看一下:
22 =4
42 =16
62 + 12 =37
72 + 32 =58
82 + 52 =89
92 + 82 =145
52 + 42 + 12 =42
22 + 42 =20
02 + 22 =4
42 =16
62 + 12 =37
72 + 32 =58
82 + 52 =89
92 + 82 =145
52 + 42 + 12 =42
22 + 42 =20
02 + 22 =4
42 =16
62 + 12 =37
72 + 32 =58
82 + 52 =89
92 + 82 =145
52 + 42 + 12 =42
22 + 42 =20
02 + 22 =4
42 =16
62 + 12 =37
72 + 32 =58
82 + 52 =89
92 + 82 =145

可以发现,运算结果竟然是循环的。循环是4、16、37、58、89、145、42、20、4。接下来再把3的前30个步骤打印一下:

32 =9
92 =81
12 + 82 =65
52 + 62 =61
12 + 62 =37
72 + 32 =58
82 + 52 =89
92 + 82 =145
52 + 42 + 12 =42
22 + 42 =20
02 + 22 =4
42 =16
62 + 12 =37
72 + 32 =58
82 + 52 =89
92 + 82 =145
52 + 42 + 12 =42
22 + 42 =20
02 + 22 =4
42 =16
62 + 12 =37
72 + 32 =58
82 + 52 =89
92 + 82 =145
52 + 42 + 12 =42
22 + 42 =20
02 + 22 =4
42 =16
62 + 12 =37
72 + 32 =58
发现循环竟然和2是相同的,不过是从58开始,58、89、145、42、20、4、16、37、58。
通过打印其他数的运算步骤,发现也是这样的一个循环,只是进入循环的数不同。
因此只要在运算过程中出现了58、89、145、42、20、4、16、37这几个数中的任意一个,就可以断定这个数不是happy数。
我的代码就根据58是否出现,来判断一个数是否为happy数。
实现代码

class Solution {
    public boolean isHappy(int n) {
		for(int i = n;;) {
			i = Count(i);
			if(i == 1) {
				return true;
			}
			if(i == 58) {
				return false;
			}
		}
    }
	public int Count(int num) {
		int ans = num;
		int b =0;
	        while(ans > 0) {
	        	b += (ans%10) * (ans%10);
	        	ans = ans/10;
	        }
	        ans = b;
		return ans;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值