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.
Requirements for atoi:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
思路:
1.首先分析输入字符串的特点,开始有空格,后面可能有“+”和“-”,接着跟着数字,数字后面的字符都忽略。
2.需要考虑的特殊情况,a.字符串是否为空,返回0;b.除空格外的第一个字符不是“+”“-”和数字,返回0;c.字符串只包含空格和无效字符,返回0;
3.在字符串转int时,要考虑越界问题,还要考虑正负号问题,因为不能使用Integer.parseInt()方法,因为此方法只能返回int型,而我需要先返回一个long类型的。
代码:
public class Solution {
public int myAtoi(String str){
StringBuffer sb=new StringBuffer();
boolean flag=false;
int m=0;
long tmp=0;
if(str.isEmpty()) return 0;
else{
for(int i=0;i<str.length();i++){
if(str.charAt(i)==' ') continue;
//除空格外第一次遇到+或者-的时候
else if((str.charAt(i)=='+')||(str.charAt(i)=='-')) {
sb.append(str.charAt(i));
for(int j=i+1;j<str.length();j++){
if((str.charAt(j)>='0')&&(str.charAt(j)<='9')) sb.append(str.charAt(j));
else break;
}
if(sb.length()==1) return 0;
else break;
}
//除空格外第一次遇到的是数字的时候
else if((str.charAt(i)>='0')||(str.charAt(i)<='9')){
for(int p=i;p<str.length();p++){
if((str.charAt(p)>='0')&&(str.charAt(p)<='9')) sb.append(str.charAt(p));
else break;
}
break;
}
else break;
}
if(sb.length()==0) return 0;
if(sb.charAt(0)=='+'){
m=1;
}
else if(sb.charAt(0)=='-'){
m=1;
flag=true;
}
//字符串转long型整数
int k=sb.length()-1;
for(int p=m;p<=k;p++){
tmp+=(sb.charAt(p)-'0')*Math.pow(10,k-p);
}
if(flag){
tmp=(-1)*tmp;
}
if(tmp>=Integer.MAX_VALUE) return Integer.MAX_VALUE;
else if(tmp<=Integer.MIN_VALUE) return Integer.MIN_VALUE;
else return (int)tmp;
}
}
}