题目:
Implement atoi to convert a string to an integer.
思路与步骤:
1. 判断字符串是否为控字符串;
2. 去掉开头的空格;
3. 判断开始位是否有正负;
4. 转换,同时注意overflow的问题。
核心步骤:
String逐个字符从左往右遍历,若为数字,则 result = String当前位的int值;
此后,String每向右读一位,result =result当前值*10 + String当前位的int值。
注意事项:
1. 该题目最大的问题是不能考虑到全部的情况,如:开头有空格;有正负号;有int型的溢出等。
2. 在正负号问题上,用if判断来分别执行转换比较麻烦,这里定义一个int型值sign,用来存储 1 和 -1,来表示正负,可以简化代码。
Java程序实现:
public class Solution {
public int myAtoi(String str) {
int intdata = 0, sign = 1, i = 0;
int sLen = str.length();
//1. empty string
if(sLen == 0) return 0;
//2. Delete spacings
while (str.charAt(i) == ' ') i++;
//3. plus or minus
if(str.charAt(i) == '+'){
sign = 1;
i++;
} else if(str.charAt(i) == '-'){
sign = -1;
i++;
}
//4. convert number and avoid overflow
for(i = i; i < sLen; i++){
if(str.charAt(i)-'0' > 9 || str.charAt(i)-'0' < 0) break;
if(sign == 1 &&
((intdata==Integer.MAX_VALUE/10 && str.charAt(i)-'0'>Integer.MAX_VALUE%10) || intdata>Integer.MAX_VALUE/10))
return Integer.MAX_VALUE;
if(sign == -1 &&
((intdata==Integer.MIN_VALUE/10 && str.charAt(i)-'0'>-1*(Integer.MIN_VALUE%10)) || intdata<-1*Integer.MIN_VALUE/10))
return Integer.MIN_VALUE;
intdata = sign * (str.charAt(i) - '0' + sign * intdata * 10);
}
return intdata;
}
}
改进后的Java程序:
public class Solution {
public int myAtoi(String str) {
int intdata = 0, sign = 1, i = 0;
int sLen = str.length();
//1. empty string
if(sLen == 0) return 0;
//2. Delete spacings
while (str.charAt(i) == ' ') i++;
//3. plus or minus
if(str.charAt(i) == '+' || str.charAt(i) == '-'){
sign = (str.charAt(i) == '+') ? 1 : -1;
i++;
}
//4. convert number and avoid overflow
for(i = i; i < sLen; i++){
if(str.charAt(i)-'0' > 9 || str.charAt(i)-'0' < 0) break;
//avoid overflow
if((sign*intdata==Integer.MAX_VALUE/10 && str.charAt(i)-'0'>Integer.MAX_VALUE%10) || sign*intdata>Integer.MAX_VALUE/10)
return sign==1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
intdata = sign * (str.charAt(i) - '0' + sign * intdata * 10);
}
return intdata;
}
}
C程序:
int myAtoi(char* str) {
int sLen = strlen(str);
int intdata = 0, sign = 1, i = 0;
//1. empty string
if(sLen == 0) return 0;
//2. Delete spacings
while (str[i] == ' ') i++;
//3. plus or minus
if(str[i] == '+' || str[i] == '-'){
sign = (str[i] == '+') ? 1 : -1;
i++;
}
//4. convert number and avoid overflow
for(i = i; i < sLen; i++){
if(str[i]-'0' > 9 || str[i]-'0' < 0) break;
//avoid overflow
if((sign*intdata==INT_MAX/10 && str[i]-'0'>INT_MAX%10) || sign*intdata>INT_MAX/10)
return sign==1 ? INT_MAX : INT_MIN;
intdata = sign * (str[i] - '0' + sign * intdata * 10);
}
return intdata;
}