Skip to content

Commit 9b54c25

Browse files
committedJan 15, 2023
Add solution #202
1 parent 46e6165 commit 9b54c25

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@
103103
190|[Reverse Bits](./0190-reverse-bits.js)|Easy|
104104
191|[Number of 1 Bits](./0191-number-of-1-bits.js)|Easy|
105105
198|[House Robber](./0198-house-robber.js)|Medium|
106+
202|[Happy Number](./0202-happy-number.js)|Easy|
106107
203|[Remove Linked List Elements](./0203-remove-linked-list-elements.js)|Easy|
107108
204|[Count Primes](./0204-count-primes.js)|Medium|
108109
206|[Reverse Linked List](./0206-reverse-linked-list.js)|Easy|

‎solutions/0202-happy-number.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* 202. Happy Number
3+
* https://leetcode.com/problems/happy-number/
4+
* Difficulty: Easy
5+
*
6+
* Write an algorithm to determine if a number n is happy.
7+
*
8+
* A happy number is a number defined by the following process:
9+
* - Starting with any positive integer, replace the number by the sum of the squares of its digits.
10+
* - Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a
11+
* cycle which does not include 1.
12+
* - Those numbers for which this process ends in 1 are happy.
13+
*
14+
* Return true if n is a happy number, and false if not.
15+
*/
16+
17+
/**
18+
* @param {number} n
19+
* @return {boolean}
20+
*/
21+
var isHappy = function(n) {
22+
while (n !== 1) {
23+
n = [...String(n)].reduce((sum, digit) => sum + digit ** 2, 0);
24+
if (n === 4) {
25+
return false;
26+
}
27+
}
28+
return true;
29+
};

0 commit comments

Comments
 (0)
Please sign in to comment.