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.
用正数去判断也没问题:ret>(Integer.MAX_VALUE-(c-'0')/dw)
当为负数时用正数去算,满足ret>(Integer.MAX_VALUE-(c-'0')/dw) 超过了,设置为Integer.MIN_VALUE;
public class Solution {
public int myAtoi(String str) {
if(str==null || str.length()==0)
return 0;
str=str.trim();
int ret=0;
boolean isPosi=true;
for(int i=0;i<str.length();i++){
if(i==0&&(str.charAt(i)=='-')){
isPosi=false;
}else if( i==0&&str.charAt(i)=='+'){
isPosi=true;
}
else if(str.charAt(i)>='0' && str.charAt(i)<='9'){
char c=str.charAt(i);
if(ret>(Integer.MAX_VALUE-(c-'0'))/10){
return isPosi? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
ret*=10;
ret += c - '0';
}
else{
return isPosi?ret:-ret;
}
}
return isPosi?ret:-ret;
}
}