【LeetCode】快乐数

Happy Number   题目

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.

Example: 

Input: 19
Output: true
Explanation: 
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

这个题目最开始自己想到的思路比较直接,while循环,且限定循环次数为10086,来表示当结果不为1时的无限次循环,显而易见,执行用时很长,44ms。哎,脑子是真的懒也真的笨。

看了题解简直惊为天人,然后自己动手算了算,果然发现规律:

(1)快乐数最后结果是1,也可以看做是关于1循环;

(2)不快乐数计算过程中有死循环,且任意不快乐数的循环体总有4-16-37-58-89-145-42-20-4。

即题目可以通过判断是否存在循环及存在循环时的数据是否为1来判断一个数是否快乐数。

思路一:哈希表

哈希表是通过哈希函数使关键字和其存储位置一一对应建立的表。若关键字为1则返回true;若不为1,则判断该关键字是否在哈希表中,若在表明循环出现,返回false,若不存在,则将该关键字存入哈希表,继续循环。

哈希表可通过<set>、<map>实现。

代码如下:

bool isHappy(int n) {//哈希表 
		set<int> st;
		int sum=0,k;
		while(1)
		{	
			while(n)
			{
				k=n%10;
				sum+=k*k;
				n/=10; 
			}
			if(sum==1)
				return true;
			else
			{
				if(st.find(sum)==st.end())
				{
					st.insert(sum);
					n=sum;
					sum=0; 
				}
				else
					return false;//表明出现循环 
			}
		}
		return true; 
}

思路二:快慢指针

就像环形跑道上跑步一样,不一样速度的两个人总会相遇,但是在非直线跑道上,两个人一定不会相遇。所以如果速度不一样的两个人相遇,则一定是在环形跑道部分。

所以可以用快慢指针来解决循环问题,找出循环。慢指针每次走一步,快指针每次走两步,当两者相遇时,即发生了循环,在循环体内。

所以可以判断快慢指针相等时的值,若是1,返回true;否则,返回false。

代码如下:

int squaresSum(int n)
	{
		int k,sum=0;
		while(n)
		{
			k=n%10;
			sum+=k*k;
			n/=10;
		}	
		return sum;
	} 
    bool isHappy(int n) {//快慢指针 
		int slow=n; 
		int fast=n;
		do{
			slow=squaresSum(slow);
			fast=squaresSum(fast);
			fast=squaresSum(fast);
		}while(fast!=slow);
		return slow==1;
    }

该题目类似于环形链表环形链表,判断一个链表中是否有环,也用这两种思路。

即涉及到循环的题目可以考虑哈希表和快慢指针。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值