算法笔记: 力扣#202 快乐数

问题描述


解法


分析

Python 实现

1
2
3
4
5
6
7
8
9
10
11
class :
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
seen = set()
while n not in seen:
seen.add(n)
n = sum(int(num)**2 for num in str(n))
return n == 1

Java 实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class {
public boolean isHappy(int n) {
Set<Integer> seen = new HashSet<>();
while(!seen.contains(n)){
seen.add(n);
int sum = 0;
while(n!=0){
sum += Math.pow(n%10,2);
n = n/10;
}
n = sum;
}
return n==1;
}
}

链接


202. Happy Number
202. 快乐数
(English version) Algorithm Notes: Leetcode#202 Happy Number