File tree Expand file tree Collapse file tree 3 files changed +59
-0
lines changed
leetcode/palindrome-number Expand file tree Collapse file tree 3 files changed +59
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Palindrome Number
2
+
3
+ ## Description
Original file line number Diff line number Diff line change
1
+ // solve without converting to string
2
+ const isPalindrome = ( x ) => {
3
+ if ( x < 0 ) {
4
+ return false ;
5
+ }
6
+
7
+ let reverse = 0 ;
8
+ const original = x ;
9
+
10
+ while ( x > 0 ) {
11
+ reverse = ( reverse * 10 ) + ( x % 10 ) ;
12
+ x = Math . floor ( x / 10 ) ;
13
+ }
14
+
15
+ return original === reverse ;
16
+ } ;
17
+
18
+ // solve by converting to string
19
+ const isPalindrome2 = ( x ) => x . toString ( ) === [ ...x . toString ( ) ] . reverse ( ) . join ( '' ) ;
20
+
21
+ module . exports = {
22
+ isPalindrome,
23
+ isPalindrome2,
24
+ } ;
Original file line number Diff line number Diff line change
1
+ const { isPalindrome, isPalindrome2 } = require ( './solution' ) ;
2
+
3
+ describe ( 'Palindrome Number' , ( ) => {
4
+ const testCases = [
5
+ {
6
+ input : 121 ,
7
+ output : true ,
8
+ } ,
9
+ {
10
+ input : - 121 ,
11
+ output : false ,
12
+ } ,
13
+ {
14
+ input : 10 ,
15
+ output : false ,
16
+ } ,
17
+ {
18
+ input : - 101 ,
19
+ output : false ,
20
+ } ,
21
+ ] ;
22
+
23
+ it ( 'should return a boolean type' , ( ) => {
24
+ expect ( typeof isPalindrome ( 121 ) ) . toBe ( 'boolean' ) ;
25
+ expect ( typeof isPalindrome2 ( 121 ) ) . toBe ( 'boolean' ) ;
26
+ } ) ;
27
+
28
+ it . each ( testCases ) ( 'should return $output' , ( testCase ) => {
29
+ expect ( isPalindrome ( testCase . input ) ) . toBe ( testCase . output ) ;
30
+ expect ( isPalindrome2 ( testCase . input ) ) . toBe ( testCase . output ) ;
31
+ } ) ;
32
+ } ) ;
You can’t perform that action at this time.
0 commit comments