-
Notifications
You must be signed in to change notification settings - Fork 0
/
8-stringToInteger(atoi).js
122 lines (116 loc) · 3.67 KB
/
8-stringToInteger(atoi).js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
var myAtoi = function (str) {
let removeInitialWhiteSpace = function (str) {
let string = str;
while (string[0] === " ") {
string = string.slice(1, string.length);
}
return string;
};
let stringToArray = function (string) {
let arr = [];
let first = true;
let cont = true;
while (cont) {
switch (string[0]) {
case "0":
arr.push(0);
string = string.slice(1, string.length);
first = false;
break;
case "1":
arr.push(1);
string = string.slice(1, string.length);
first = false;
break;
case "2":
arr.push(2);
string = string.slice(1, string.length);
first = false;
break;
case "3":
arr.push(3);
string = string.slice(1, string.length);
first = false;
break;
case "4":
arr.push(4);
string = string.slice(1, string.length);
first = false;
break;
case "5":
arr.push(5);
string = string.slice(1, string.length);
first = false;
break;
case "6":
arr.push(6);
string = string.slice(1, string.length);
first = false;
break;
case "7":
arr.push(7);
string = string.slice(1, string.length);
first = false;
break;
case "8":
arr.push(8);
string = string.slice(1, string.length);
first = false;
break;
case "9":
arr.push(9);
string = string.slice(1, string.length);
first = false;
break;
case "+":
if (first === true) {
string = string.slice(1, string.length);
first = false;
break;
} else {
cont = false;
break;
}
case "-":
if (first === true) {
arr.push("-");
string = string.slice(1, string.length);
first = false;
break;
} else {
cont = false;
break;
}
default:
cont = false;
break;
}
}
return arr;
};
let arrayToInteger = function (arr) {
let negative = false;
if (arr[0] === "-") {
negative = true;
arr.shift();
}
let result = 0;
while (arr.length > 0) {
result *= 10;
result += arr[0];
arr.shift();
}
negative ? (result = -1 * result) : result;
return result;
};
let result = arrayToInteger(stringToArray(removeInitialWhiteSpace(str)));
if (result < -2147483648) {
return -2147483648;
} else if (result > 2147483647) {
return 2147483647;
} else {
return result;
}
};
let str = " 123";
console.log(myAtoi("91283472332"));