8. String to Integer (atoi)
https://leetcode.com/problems/string-to-integer-atoi/
js
/**
* @param {string} str
* @return {number}
*/
var myAtoi = function(str) {
const INT_MAX = 2147483647
const INT_MIN = -2147483648
if (!str) {
return 0
}
var i = 0
var result = 0
var sign = 1
str = str.trim()
if (str[i] === '+') {
i++
} else if (str[i] === '-') {
sign = -1
i++
}
while (i < str.length && str[i] >= '0' && str[i] <= '9') {
let num = +str[i]
if (result > (INT_MAX - num) / 10) {
return sign > 0 ? INT_MAX : INT_MIN
}
result = result * 10 + num
i++
}
return sign * result
}
py
class Solution(object):
def myAtoi(self, s):
"""
:type s: str
:rtype: int
"""
INT_MAX, INT_MIN = 2147483647, -2147483648
if not s:
return 0
i, result, sign = 0, 0, 1
s = s.strip()
if s[i] == '+':
i += 1
elif s[i] == '-':
sign = -1
i += 1
while i < len(s) and s[i] >= '0' and s[i] <= '9':
num = int(s[i])
if result > (INT_MAX - num) / 10:
return INT_MAX if sign > 0 else INT_MIN
result = result * 10 + num
i += 1
return sign * result
go
import "math"
func myAtoi(str string) int {
if len(str) == 0 {
return 0
}
var result int32 = 0
var sign int32 = 1
i := 0
for str[i] == ' ' {
i++
}
if str[i] == '+' {
i++
} else if str[i] == '-' {
sign = -1
i++
}
for i < len(str) && str[i] >= '0' && str[i] <= '9' {
num := int32(str[i] - '0')
if result > (math.MaxInt32-num)/10 {
if sign > 0 {
return math.MaxInt32
}
return math.MinInt32
}
result = result*10 + num
i++
}
return int(sign * result)
}