Skip to content

Commit 47d626c

Browse files
authored
Update 8-string-to-integer-(atoi).js
1 parent db08b24 commit 47d626c

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

8-string-to-integer-(atoi).js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,33 @@
55
const myAtoi = function(str) {
66
return Math.max(Math.min(parseInt(str) || 0, 2147483647), -2147483648);
77
};
8+
9+
// anotther
10+
11+
/**
12+
* @param {string} s
13+
* @return {number}
14+
*/
15+
const myAtoi = function(s) {
16+
let n = s.length, i = 0, j = 0, sign = 1;
17+
if(n === 0) {
18+
return 0;
19+
}
20+
while(i < n && s[i] === ' ') {
21+
i++;
22+
}
23+
if(i < n && (s[i] === '-' || s[i] === '+')) {
24+
sign = (s[i] === '-') ? -1 : 1;
25+
i++;
26+
}
27+
j = i
28+
while(i < n) {
29+
if(Number.isInteger(parseInt(s[i]))) i++;
30+
else break;
31+
}
32+
let result = parseInt(s.slice(j, i))
33+
if(isNaN(result)) return 0
34+
if(sign * result < -(2**31)) return -(2**31);
35+
else if(sign * result > (2**31-1)) return 2**31-1;
36+
else return sign * result;
37+
};

0 commit comments

Comments
 (0)