题目
编写一个算法来判断一个数 n 是不是快乐数。
「快乐数」定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。如果 可以变为 1,那么这个数就是快乐数。
如果 n 是快乐数就返回 True ;不是,则返回 False 。
示例:
输入:19
输出:true
解释:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
解题思路
解法一:HashSet
遍历当前数字n,把n的各位的平方和作为新的n,
1)如果等于1,则返回True;
2)如果已经在集合中出现,则返回False;
3)否则将其加入到集合中。
解法二:快慢指针
在算法的每一步中,慢速在链表中前进 1 个节点,快跑者前进 2 个节点。
1)如果 n 是一个快乐数,即没有循环,那么快跑者最终会比慢跑者先到达数字 1;
2)如果 n 不是一个快乐的数字,那么最终快跑者和慢跑者将在同一个数字上相遇。
代码
解法一:HashSet
Python代码如下:
class Solution:
def getSquare(self, num):
res = 0
while num != 0:
res += (num%10)**2
num //= 10
return res
def isHappy(self, n: int) -> bool:
visited = set()
res = n
while True:
res = self.getSquare(res)
if res == 1:
return True
elif res in visited:
return False
else:
visited.add(res)
Java代码如下:
class Solution {
public boolean isHappy(int n) {
Set<Integer> visited = new HashSet<>();
int res = n;
while(true){
res = getSquare(res);
if(res==1){
return true;
}else if(visited.contains(res)){
return false;
}else{
visited.add(res);
}
}
}
private int getSquare(int num){
int res = 0;
while(num!=0){
res += (num%10)*(num%10);
num /= 10;
}
return res;
}
}
解法二:快慢指针
Python代码如下:
class Solution:
def isHappy(self, n: int) -> bool:
def getSquare(num):
res = 0
while num != 0:
res += (num%10)**2
num //= 10
return res
slow = n
fast = n
while True:
slow = getSquare(slow)
fast = getSquare(getSquare(fast))
if fast == slow:
break
return True if fast == 1 else False
Java代码如下:
class Solution {
public boolean isHappy(int n) {
int slow = n;
int fast = n;
while(true){
slow = getSquare(slow);
fast = getSquare(getSquare(fast));
if(slow == fast){
break;
}
}
if(fast == 1){
return true;
}else{
return false;
}
}
private int getSquare(int num){
int res = 0;
while(num!=0){
res += (num%10)*(num%10);
num /= 10;
}
return res;
}
}
本文介绍了一种用于判断正整数是否为快乐数的算法。快乐数是指通过不断将该数的每位数字平方和进行迭代,最终能变为1的数字。文章提供了两种解法:使用HashSet避免循环和利用快慢指针检测循环。
259

被折叠的 条评论
为什么被折叠?



