classSolution{publicintstrToInt(String str){// 去除首尾空格char[] strArr = str.trim().toCharArray();if(strArr.length ==0){return0;}int ans =0;int index =0;boolean isNegative =false;// 首位为 + - 的情况if(strArr[0]=='-'|| strArr[0]=='+'){
index++;
isNegative =(strArr[0]=='-');}// 顺带排除第一个非空字符无效的情况了for(; index < strArr.length && strArr[index]>='0'&& strArr[index]<='9'; index++){// 溢出的情况:负数 && 正数if(isNegative){if(ans >214748364||(ans ==214748364&& strArr[index]>'8')){return-2147483648;}}// 正数情况elseif(ans >214748364||(ans ==214748364&& strArr[index]>'7')){return2147483647;}
ans *=10;
ans += strArr[index]-'0';}if(isNegative){
ans *=-1;}return ans;}}
二刷
只能说老业务题了
classSolution{publicintstrToInt(String str){char[] arr = str.trim().toCharArray();if(arr.length ==0){return0;}int isNegative = arr[0]=='-'?1:0;int ans =0;if(arr[0]>='0'&& arr[0]<='9'){
ans = arr[0]-'0';}elseif(arr[0]!='+'&& arr[0]!='-'){return ans;}for(int i =1; i < arr.length; i++){// case 1: 中断if(arr[i]<'0'|| arr[i]>'9'){break;}// case 2: 越界if((ans >214748364)||(ans ==214748364&& arr[i]-'0'>7+ isNegative)){
ans = isNegative ==1?Integer.MIN_VALUE :Integer.MAX_VALUE;break;}// case 3: 继续
ans *=10;
ans += arr[i]-'0';}return isNegative ==1?-1* ans : ans;}}