實現 atoi:將字符串轉換為 32 位有符號整數。需處理前導空格、可選正負號、數字字符、非數字截停、溢出鉗制 (INT_MIN=-2³¹, INT_MAX=2³¹-1)。
+ 或 -。| 輸入 | 輸出 | 說明 |
|---|---|---|
"42" | 42 | 正常 |
" -42" | -42 | 前導空格+負號 |
"4193 with words" | 4193 | 非數字截停 |
"words and 987" | 0 | 首非數字無有效轉換 |
"-91283472332" | -2147483648 | 負溢出鉗制 INT_MIN |
"+1" | 1 | 顯式正號 |
" 0000000000012345" | 12345 | 前導零 |
"" 或 " " | 0 | 空/全空格 |
public class Solution {
public int myAtoi(String str) {
if (str == null) return 0;
str = str.trim(); // 去除首尾空格
if (str.isEmpty()) return 0;
int sign = 1, i = 0;
if (str.charAt(0) == '-') { sign = -1; i++; }
else if (str.charAt(0) == '+') { i++; }
long result = 0;
for (; i < str.length(); i++) {
char c = str.charAt(i);
if (c < '0' || c > '9') break;
result = result * 10 + (c - '0');
// 溢出檢查
if (sign == 1 && result > Integer.MAX_VALUE) return Integer.MAX_VALUE;
if (sign == -1 && -result < Integer.MIN_VALUE) return Integer.MIN_VALUE;
}
return sign * (int)result;
}
}
class Solution {
public:
int myAtoi(string str) {
int i = 0, n = str.size();
// 1. 跳過空格
while (i < n && str[i] == ' ') i++;
if (i == n) return 0;
// 2. 符號
int sign = 1;
if (str[i] == '-') { sign = -1; i++; }
else if (str[i] == '+') { i++; }
// 3. 數字累積
long long result = 0;
while (i < n && isdigit(str[i])) {
result = result * 10 + (str[i] - '0');
// 4. 溢出鉗制
if (sign == 1 && result > INT_MAX) return INT_MAX;
if (sign == -1 && -result < INT_MIN) return INT_MIN;
i++;
}
return sign * (int)result;
}
};