algorithm notes: leetcode#202 happy number

Problem


Solution


Analysis

Python implementation

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 implementation

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 快乐数