问题描述:将一个字符串转换为整数,转换时会丢弃开头无用空白字符,若首字符为+,-,或数字,转换为相应的正负数,否则返回0,数字后面如果存在其他非数字字符,则舍弃。
例:
" 142a"输出为142
" -10 k"输出为-10
"ws120"输出为0注意:假设可转换整型大小为32位,如果转换数据超出范围,返回最大最小值[-231, 231-1]。
思路:考察到所有情况即可
- 先将字符串转换为整形数组,遍历判断
- 直接遍历判断
- 正则表达式
//java
//先转后判断
class Solution {
public int myAtoi(String str) {
int[] cp = str.codePoints().toArray();//转换成整形数组
long z = 0;
int index = 0, flag = 0, sign = 1;//index表示遍历下标,flag指代是否遇到可转字符,sign指代正负号
index = 0;
while(index < str.length()){ //遍历
if(cp[index] == 32){//是否为空格
if(flag == 0) ++index;//前面空格跳过
else break;//后面直接跳出遍历
}else if(cp[index] == 43 || cp[index] == 45){
if(flag == 0){//正负号在前,置数flag
sign = (cp[index] == 43) ? 1 : -1;
flag = 1;
++index;
}else break;//位置不合法,跳出
} else if(cp[index] < 48 || cp[index] > 57){
if(flag == 0) return 0;//先遇到非可转换字符,直接跳出
else break;
} else if(cp[index] >= 48 && cp[index] <= 57){//遇到数字,直接记录
z = z * 10 + cp[index++] - 48;
long temp = z * sign;//防止越界,定义为long型
//越界返回预定义值
if(temp < Integer.MIN_VALUE) return Integer.MIN_VALUE;
else if(temp > Integer.MAX_VALUE) return Integer.MAX_VALUE;
flag = 1;
}
}
return (int)(sign * z);
}
}
//直接遍历判断,比第一个方法更便捷
class Solution {
public int myAtoi(String str) {
int res = 0;
if(str.length() == 0 || str == null) return 0;//数组为空
int index = 0;//下标
while(index < str.length() && str.charAt(index) == ' '){
++index;//跳过前面的空格
}
if(index == str.length()) return 0;//跳完无元素
int sign = 1;//符号标志
if(str.charAt(index) == '-'){
sign = -1;
++index;
}
else if(str.charAt(index) == '+'){
++index;
}
for(; index < str.length(); ++index){//找数字
int ch = str.charAt(index);
if(ch < '0' || ch > '9') break;//跳过后续字符
//判断是否溢出
if(res == Integer.MAX_VALUE/10 && ch - '0' > Integer.MAX_VALUE%10 && sign > 0)
return Integer.MAX_VALUE;
if(res == Integer.MAX_VALUE/10 && ch - '0' > -(Integer.MIN_VALUE%10) && sign < 0)
return Integer.MIN_VALUE;
if(res > Integer.MAX_VALUE/10 && sign > 0) return Integer.MAX_VALUE;
if(res > -(Integer.MIN_VALUE/10) && sign < 0) return Integer.MIN_VALUE;
res = res * 10 + ch -'0';
}
return sign * res;
}
}
//正则表达式
import java.util.regex.*;
class Solution {
public int myAtoi(String str) {
str = str.trim();//去掉首尾空字符
Pattern p = Pattern.compile("^[\\-\\+]?\\d+");//正则表达式匹配
Matcher m = p.matcher(str);
int value = 0;
if(m.find()){//匹配成功则判断是否溢出
try{
value = Integer.parseInt(str.substring(m.start(),m.end()));//不溢出转换为整型
}catch (Exception e){
return str.charAt(0) == '-' ? Integer.MIN_VALUE : Integer.MAX_VALUE;//溢出根据符号返回对应值
}
}
return value;
}
}