題目:
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;
}