题目链接
思路
java
public int myAtoi(String s) {
int length = s.length();
char[] chars = s.toCharArray();
int index = 0;
while (index < length && chars[index] == ' ') {
index++;
}
if (index == length) {
return 0;
}
boolean flag = true;
char first = chars[index];
if (first == '+') {
index++;
} else if (first == '-') {
index++;
flag = false;
}
int res = 0;
while (index < length) {
char c = chars[index];
if (c > '9' || c < '0') {
break;
}
if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && (c - '0') > Integer.MAX_VALUE % 10)) {
return flag ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
res = res * 10 + (c - '0');
index++;
}
return flag ? res : -res;
}
go
func myAtoi(s string) int {
length := len(s)
arr := []rune(s)
index := 0
for index < length && arr[index] == ' ' {
index++
}
if index == length {
return 0
}
flag := true
if arr[index] == '+' {
index++
} else if arr[index] == '-' {
index++
flag = false
}
res := 0
for index < length {
c := arr[index]
if c > '9' || c < '0' {
break
}
r := (int)(c - '0')
if res > math.MaxInt32/10 || (res == math.MaxInt32/10 && r > math.MaxInt32%10) {
if flag {
return math.MaxInt32
}
return math.MinInt32
}
res = res*10 + r
index++
}
if flag {
return res
}
return -res
}
|