File tree Expand file tree Collapse file tree 1 file changed +53
-0
lines changed
Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @param {string } str
3+ * @return {number }
4+ */
5+
6+ let isNegative ;
7+ var myAtoi = function ( str ) {
8+ isNegative = 0 ;
9+ str = str . trim ( ) ;
10+
11+ if ( str [ 0 ] === "-" || str [ 0 ] === "+" || ! isNaN ( str [ 0 ] ) ) {
12+ if ( str [ 0 ] === "+" ) {
13+ return checkNumber ( str , 1 ) ;
14+ } else if ( ! isNaN ( str [ 0 ] ) ) {
15+ return checkNumber ( str , 0 ) ;
16+ } else {
17+ if ( str [ 0 ] === "-" ) {
18+ isNegative = 1 ;
19+ str = str . substring ( 1 , str . length ) ;
20+
21+ return checkNumber ( str , 0 ) ;
22+ }
23+ }
24+ } else {
25+ return 0 ;
26+ }
27+ } ;
28+
29+ let checkNumber = ( currentString , currentIndex ) => {
30+ let newNumber = "" ;
31+ let INT_MIN = Math . pow ( - 2 , 31 ) ;
32+ let INT_MAX = Math . pow ( 2 , 31 ) - 1 ;
33+
34+ for ( let i = 0 ; i < currentString . length ; currentIndex ++ , i ++ ) {
35+ if ( isNaN ( currentString . charAt ( currentIndex ) ) )
36+ break ;
37+
38+ if ( currentString . charAt ( currentIndex ) === " " )
39+ break ;
40+
41+ newNumber += currentString . charAt ( currentIndex ) ;
42+ }
43+
44+ if ( isNegative )
45+ newNumber *= - 1 ;
46+
47+ if ( newNumber < INT_MIN )
48+ return INT_MIN ;
49+ else if ( newNumber > INT_MAX )
50+ return INT_MAX ;
51+
52+ return newNumber ;
53+ }
You can’t perform that action at this time.
0 commit comments