Skip to content

Commit 955dc86

Browse files
authored
add 202-Happy-Number
1 parent c61789b commit 955dc86

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

javascript/202-Happy-Number.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
function isHappy(n) {
2+
const visit = new Set();
3+
4+
while (!visit.has(n)) {
5+
visit.add(n);
6+
n = sumOfSquares(n);
7+
8+
if (n == 1) return true;
9+
}
10+
11+
return false;
12+
}
13+
14+
function sumOfSquares(n) {
15+
let output = 0;
16+
17+
while (n) {
18+
let digit = n % 10;
19+
digit = digit ** 2;
20+
output += digit;
21+
n = Math.floor(n / 10);
22+
}
23+
24+
return output;
25+
}

0 commit comments

Comments
 (0)