8. 字符串转换整数 (atoi)
8. String to Integer (atoi)
题目描述
LeetCode8. String to Integer (atoi)中等
Java 实现
class Solution {
public int myAtoi(String str) {
if (str == null || str.trim().length() == 0) {
return 0;
}
str = str.trim();
char firstChar = str.charAt(0);
int sign = 1, start = 0, len = str.length();
long sum = 0;
if (firstChar == '+') {
sign = 1;
start++;
} else if (firstChar == '-') {
sign = -1;
start++;
}
for (int i = start; i < len; i++) {
if (!Character.isDigit(str.charAt(i))) {
return (int) sum * sign;
}
sum = sum * 10 + str.charAt(i) - '0';
if (sign == 1 && sum > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
if (sign == -1 && sign * sum < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
}
return (int) sum * sign;
}
}
相似题目
参考资料