Description
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:
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
分析
题目的意思是:判断一个数是否是开心数。
- 这是leetcode上的easy题目。
- 关键是怎么判断循环的存在,这里用了一个set存放已经出现过的数字,所以后面只需要判断数字在set是否出现过就可以判断是否有循环了,如果有循环,则数字一定会在set里面再出现,这样就找到了终止条件了。
C++实现
class Solution {
public:
bool isHappy(int n) {
set<int> s;
while(n!=1){
int t=0;
while(n>0){
t+=(n%10)*(n%10);
n=n/10;
}
n=t;
if(s.count(t)){
break;
}else{
s.insert(t);
}
}
return n==1;
}
};
Python实现
用一个集合存放已经遍历过的数,然后判断重复即可,当然答案还提供了另一种方法,就是够用快慢指针,判断是否存在一个无限循环,这个思路还挺好的。
class Solution:
def isHappy(self, n: int) -> bool:
visited = set()
visited.add(n)
while n!=1:
h_val=0
while n>0:
h_val += (n%10)*(n%10)
n=n//10
n=h_val
if n in visited:
return False
else:
visited.add(n)
return True