-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring_to_integer.js
More file actions
47 lines (32 loc) · 970 Bytes
/
Copy pathstring_to_integer.js
File metadata and controls
47 lines (32 loc) · 970 Bytes
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
/**
* @param {string} s
* @return {number}
*/
const MAX_INT = 2 ** 31 - 1
const MIN_INT = -MAX_INT - 1
var myAtoi = function (str) {
const integer = getIntegerFrom(str)
if (integer > MAX_INT) return MAX_INT
if (integer < MIN_INT) return MIN_INT
return integer
}
const getIntegerFrom = (str) => {
let isNegative = null,
integer = null
const realInteger = () => (isNegative ? -1 : 1) * integer
const shouldSkipSpace = (char) =>
char === ' ' && integer == null && isNegative == null
for (const char of str) {
if (shouldSkipSpace(char)) continue
if (char === '-' || char === '+') {
if (isNegative !== null || integer !== null) return realInteger()
isNegative = char === '-'
continue
}
const charCode = char.charCodeAt(0)
if (!(charCode > 47 && charCode < 58)) return realInteger()
integer = integer * 10 + (charCode - 48)
}
return realInteger()
}
console.log(myAtoi('4193 with words'))