Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
思路:题目不是很难,但是有很多特殊输入要考虑
1.数字前面有空格 如s=“ 123456”2.数字前出现了不必要或多于的字符导致数字认证错误,输出0 如s=“ b1234” ,s=“ ++1233” , s=“ +-1121”
3.数字中出现了不必要的字符,返回字符前的数字 如s=“ 12a12” , s=“ 123 123”
4.数字越界 超过了范围(-2147483648--2147483647) 若超过了负数的 输出-2147483648 超过了正数的输出2147483647
public class Solution {
public int myAtoi(String str) {
char[] arr = str.toCharArray();
long sum = 0;//先用long
boolean start = true;//是否为开头(忽略空格)
boolean flag = false;//正负号是否出现过
boolean positive = true;//数字正负
for(int i=0;i<arr.length;i++){
if(arr[i]>='0'&&arr[i]<='9'){
if(positive&&(sum*10+arr[i]-'0'-Integer.MAX_VALUE)>=0) return Integer.MAX_VALUE;//越界输出最大值
if(!positive&&((-(sum*10+arr[i]-'0'))-Integer.MIN_VALUE<=0)){//越界输出最小值
return Integer.MIN_VALUE;
}
sum = sum*10+arr[i]-'0';
start = false;
}else if(arr[i]==' ' && start){//忽略开头的空格
continue;
}else if(arr[i]=='+' || arr[i]=='-'){
start = false;
if(!flag){//没有出现过正负号
flag = true;
if(arr[i]=='-') positive=false;
}
else return 0;//出现过正负号,返回0
}else{//除数字,空格,正负号以外,返回之前的数字
return (int) (positive?sum:-sum);
}
}
return (int) (positive?sum:-sum);
}
}