String to Integer (atoi)
Implement atoi to convert a string to an integer.
【函數說明】atoi() 函數會掃描 str 字元串,跳過前面的空白字元(例如空格,tab縮進等),直到遇上數字或正負符号才開始做轉換,而再遇到非數字或字元串結束時('\0')才結束轉換,并将結果傳回。
【傳回值】傳回轉換後的整型數;如果 str 不能轉換成 int 或者 str 為空字元串,那麼将傳回 0。如果超出Integer的範圍,将會傳回Integer最大值或者最小值。
【處理思路】按照函數說明來一步步處理。首先判斷輸入是否為null。然後使用trim()函數删掉空格。判斷是否有正負号,做一個标記。傳回的是整形數,可以使用double來暫存結果。按位來計算出結果。如果遇到非數字字元,則傳回目前結果。加上前面的正負号。結果若超出了整形範圍,則傳回最大或最小值。最後傳回處理結果。
/*
* 8. String to Integer (atoi)
* Implement atoi to convert a string to an integer.
* 2016-2-20
*/
public static int myAtoi(String str) {
if (str == null || str.length() < 1) {
return 0;
}
str = str.trim(); // kill add white spaces
int i = 0; // index of str
char flag = '+'; // default positive
if (str.charAt(0) == '-') {
flag = '-';
i++;
} else if (str.charAt(0) == '+') {
i++;
}
double res = 0;
// abandon the non-digit char; calculate the result
while (str.length() > i && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
res = res * 10 + str.charAt(i) - '0';
i++;
}
if (flag == '-') res = -1 * res;
if (res > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
} else if (res < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
return (int) res;
}