解題思路
本題第一反應就是順序遍歷字符串的每一個字符,然後根據題目要求進行判斷,顯然本題的難點就不在於算法本身,而在於對於各種情況和邊界的考慮:
(1)如何去除開頭空格字符;
- 可以通過順序遍歷字符串字符,判斷是否爲空字符,如果是跳過該字符到下一個字符,直到第一個非空字符即可
(2)如何定位並標記符號位字符;
- 定義一個變量
flag
,第一個非空字符爲'+'
標記爲1
,爲'-'
標記爲-1
(3)如何截取連續數字字符;
- 通過順序遍歷,判斷是否爲數字字符
'0'-'9'
(4)如何將連續數字字符串轉爲整數;
該數字字符-'0'
就是該數字字符對應的數值,例如:'7'-'0'=7
;- 那如果是一串連續的數字字符組成的字符串呢,如:
"123"
,此時,沒法用上面的方法直接得到,可以如下: - 設置一個
base=0
,順序遍歷“123”
: - 當遍歷到
'1'
時,base = base * 10 + '1' - '0'
,得到base = 1
- 當遍歷到
'2'
時,base = base * 10 + '2' - '0' = 1 * 10 + 2
,得到base = 12
- 當遍歷到
'3'
時,base = base * 10 + '3' - '0' = 12 * 10 + 33
,得到base = 123
- 遍歷結束,得到結果爲:123
- 然後再根據符號位標記,得到最終結果,與符號位相乘
(5)如何判斷越界;
- 數值範圍爲 。如果數值超過這個範圍,返回 或
- 實現時用
Integer.valueOf()
函數拋出的異常來判斷整數越界
(6)如何考慮程序的完整性;
- 第一個非空字符既不是正號或負號,也不是數字,返回0;
- 字符串爲空,或者字符串內只包含空字符,返回0;
- 第一個非空字符是正號或負號,但接下來的第二個字符不是數字,返回0;
對於"+-2"、"+ 2"這兩種情況,都返回0
Java
代碼
class Solution {
public int myAtoi(String str) {
//如果字符串爲null或長度小於1,返回0
if(str == null || str.length() < 1) return 0;
int idx = 0; //索引
//去除開頭空格
while(idx < str.length() && str.charAt(idx) == ' '){
idx++;
}
int flag = 1; //標記正負
int base = 0; //數值
//標記符號位
if(idx < str.length() && (str.charAt(idx) == '+' || str.charAt(idx) == '-')){
flag = (str.charAt(idx) == '+') ? 1 : -1;
idx++;
}
//截取數值及越界判斷
while(idx < str.length() && str.charAt(idx) >= '0' && str.charAt(idx) <= '9'){
//Integer.MAX_VALUE=2147483647
//Integer.MIN_VALUE=-2147483648
//越界判斷
//base > Integer.MAX_VALUE / 10時,base * 10 就會越界
//base == Integer.MAX_VALUE / 10 = 214748364,base * 10 = 2147483640,最後一個數就不能大於7
if (base > Integer.MAX_VALUE / 10 || (base == Integer.MAX_VALUE / 10 && str.charAt(idx) - '0' > 7)) {
return (flag == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
// 計算轉換值
base = 10 * base + (str.charAt(idx++) - '0');
}
return base * flag;
}
}
Python3
代碼
class Solution:
def myAtoi(self, str: str) -> int:
str = str.lstrip() # 去除開頭的空格
if str == '': # 爲空
return 0
idx = 0
flag = 1
ret = '0'
if idx < len(str) and (str[idx] == '+' or str[idx] == '-'):
flag = 1 if (str[idx] == '+') else -1
idx += 1
while(idx < len(str) and str[idx].isdigit()):
ret += str[idx]
idx += 1
result = int(ret) * flag
if result > 2147483647:
return 2147483647
elif result < -2147483648:
return -2147483648
else:
return result
C++
代碼
class Solution {
public:
int myAtoi(string str) {
int i = 0;
while(' ' == str[i]) i++;// 去掉空格
int flag = 1;
if(i < str.size() && (str[i] == '+' || str[i] == '-')){
flag = (str[i] == '+') ? 1 : -1;
i++;
}
int base = 0;
while(i < str.size() && str[i] >= '0' && str[i] <= '9'){
if ((base > INT_MAX / 10) || (base == INT_MAX / 10 && (str[i] - '0') > 7)) {
return (flag == 1) ? INT_MAX : INT_MIN;
}
base = base * 10 + (str[i] - '0');
i++;
}
return base * flag;
}
};