2. 8_字符串转换整数(atoi)
/*
请你来实现一个 atoi 函数,使其能将字符串转换成整数。
*/
class Solution {
public int myAtoi(String str) {
str = str.trim();
if(str == null || str.length() == 0) return 0;
long sum = 0;
int i = 0;
int f = 1;
if(str.charAt(i) == '-' || str.charAt(i) == '+'){
f = str.charAt(i) == '-' ? -1 : 1;
i++;
}
while(i < str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9'){
sum = sum*10 + (str.charAt(i) - '0');
i++;
if(sum*f <= Integer.MIN_VALUE) return Integer.MIN_VALUE;
if(sum*f >= Integer.MAX_VALUE) return Integer.MAX_VALUE;
}
return (int)sum*f;
}
}