File tree 2 files changed +30
-0
lines changed
2 files changed +30
-0
lines changed Original file line number Diff line number Diff line change 103
103
190|[ Reverse Bits] ( ./0190-reverse-bits.js ) |Easy|
104
104
191|[ Number of 1 Bits] ( ./0191-number-of-1-bits.js ) |Easy|
105
105
198|[ House Robber] ( ./0198-house-robber.js ) |Medium|
106
+ 202|[ Happy Number] ( ./0202-happy-number.js ) |Easy|
106
107
203|[ Remove Linked List Elements] ( ./0203-remove-linked-list-elements.js ) |Easy|
107
108
204|[ Count Primes] ( ./0204-count-primes.js ) |Medium|
108
109
206|[ Reverse Linked List] ( ./0206-reverse-linked-list.js ) |Easy|
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments