File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Problem: https://leetcode.com/problems/happy-number/
2
+ // Doc: https://leetcode.com/problems/happy-number/solutions/5471203/determining-happy-numbers-efficiently/
3
+ const isHappy = ( n : number ) : boolean => {
4
+ // I assume that we cannot use string conversion to make it challenging
5
+ const visited : Record < number , boolean > = { } ;
6
+ while ( true ) {
7
+ if ( n === 1 ) return true ;
8
+ if ( n in visited ) return false ;
9
+ visited [ n ] = true ;
10
+
11
+ let sum = 0 ;
12
+ let tmp = n ;
13
+ while ( tmp > 0 ) {
14
+ const remainder = tmp % 10 ;
15
+ tmp = Math . floor ( tmp / 10 ) ;
16
+ sum += Math . pow ( remainder , 2 ) ;
17
+ }
18
+ n = sum ;
19
+ }
20
+ } ;
21
+
22
+ describe ( 'Happy Number' , ( ) => {
23
+ it ( 'should return true if the number is happy' , ( ) => {
24
+ expect ( isHappy ( 19 ) ) . toBeTruthy ( ) ;
25
+ expect ( isHappy ( 1 ) ) . toBeTruthy ( ) ;
26
+ expect ( isHappy ( 7 ) ) . toBeTruthy ( ) ;
27
+ } ) ;
28
+
29
+ it ( 'should return false if the number is not happy' , ( ) => {
30
+ expect ( isHappy ( 2 ) ) . toBeFalsy ( ) ;
31
+ expect ( isHappy ( 3 ) ) . toBeFalsy ( ) ;
32
+ } ) ;
33
+ } ) ;
You can’t perform that action at this time.
0 commit comments