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.
思路:对于给定的字符串,先跳过前面的空格字符,遇到第一个非空格的字符串,判断是不是正负号,如果是正负号,那就判断下一位字符,如果下一位字符并不是数字,直接返回0,如果是字符那就找到了数字字符串的起始下标,继续判断接下来的字符,当遇到非数字的字符时,就可以得到数字字符串的结束下标。然后根据起始下标和结束下标,在原字符串中截取子字符串。判断该子字符串是否溢出,如果溢出且符号为正,就返回int的最大值,如果溢出且符号为负,就返回int的最小值。如果未溢出那就将该字符串转为数字返回即可。
public class Solution {
public int myAtoi(String str) {
int length=str.length();
int start=0;
int end=0;
int i=0;
int sign=1;
int res=0;
String subStr="";
if(length==0) return 0;
while(i<length&&str.charAt(i)==' ')
i++;
if(str.charAt(i)=='+')
{ sign=1;
i++;
if(i<length&&!isDigital(str.charAt(i))) return 0;
}
else if(str.charAt(i)=='-')
{ sign=-1;
i++;
if(i<length&&!isDigital(str.charAt(i))) return 0;
}
if(i<length&&!isDigital(str.charAt(i))) return 0;
if(i>=length) return 0;
else start=i;
while(i<length&&isDigital(str.charAt(i))) i++;
if(i==start) end=start;
else end=i-1;
if(end-start+1>0)
subStr=str.substring(start,end+1);
if(isOverflow(subStr))
{
if(sign==1)
return 2147483647;
if(sign==-1)
return -2147483648;
}
for(int j=0;j<subStr.length();j++)
res=res*10+(subStr.charAt(j)-'0');
return res*sign;
}
public boolean isOverflow(String sub)
{
int length=sub.length();
String max="2147483647";
if(sub.equals("2147483647")) return false;
if(length<10) return false;
if(length>10) return true;
if(length==10)
{
for(int i=1;i<10;i++)
{
if(sub.charAt(i)<max.charAt(i)) return false;
}
}
return true;
}
public boolean isDigital(char ch)
{
return '0'<=ch && '9'>=ch;
}
}