Skip to content

Commit 8811db6

Browse files
committed
add: String to Integer (atoi)
1 parent e503702 commit 8811db6

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ This is the solutions collection of my LeetCode submissions, most of them are pr
1212
|2|[Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) | [JavaScript](./src/add-two-numbers/res.js)|Medium|
1313
|3|[Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) | [JavaScript](./src/longest-substring-without-repeating-characters/res.js) |Medium|
1414
|7|[Reverse Integer](https://leetcode.com/problems/reverse-integer/) | [JavaScript](./src/reverse-integer/res.js)|Easy|
15+
|8|[String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/) | [JavaScript](./src/string-to-integer-atoi/res.js)|Medium|
1516
|11|[Container With Most Water](https://leetcode.com/problems/container-with-most-water/) | [JavaScript](./src/container-with-most-water/res.js)|Medium|
1617
|13|[Roman to Integer](https://leetcode.com/problems/roman-to-integer/) | [JavaScript](./src/roman-to-integer/res.js)|Easy|
1718
|14|[Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/) | [JavaScript](./src/longest-common-prefix/res.js)|Easy|

src/string-to-integer-atoi/res.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* res.js
3+
* @authors Joe Jiang (hijiangtao@gmail.com)
4+
* @date 2017-04-03 22:44:48
5+
*
6+
* Problem: Implement atoi to convert a string to an integer.
7+
*
8+
* @param {string} str
9+
* @return {number}
10+
*/
11+
let myAtoi = function(str) {
12+
const INT_MAX = 2147483647,
13+
INT_MIN = -2147483648,
14+
bound = Number.parseInt(INT_MAX/10);
15+
let strlen = str.length,
16+
signal = 1, // 1 stands for positive number, 0 stands for negative number
17+
res = 0;
18+
19+
while (str[0] && str[0] === ' ') {
20+
str = str.slice(1);
21+
strlen -= 1;
22+
}
23+
24+
if (strlen === 0) {
25+
return 0;
26+
}
27+
28+
if(str[0] === '-') {
29+
signal = 0;
30+
str = str.slice(1);
31+
} else if (str[0] === "+") {
32+
str = str.slice(1);
33+
}
34+
35+
while (str[0] >= '0' && str[0] <= '9') {
36+
// console.log(str[0]);
37+
let element = Number.parseInt(str[0]);
38+
39+
if ( res>bound || (res===bound && element>7) ) {
40+
if(signal) {
41+
return INT_MAX;
42+
}
43+
return INT_MIN;
44+
}
45+
46+
res = res * 10 + element;
47+
str = str.slice(1);
48+
}
49+
50+
return signal? res:-res;
51+
};

0 commit comments

Comments
 (0)