记住步骤就好啦:
- 处理空字符串
- 忽略前置空格
- 保存符号
- 处理非法输入
- 处理溢出
多想无益,就住就行了。
import java.util.*;
public class Solution {
/**
*
* @param str string字符串
* @return int整型
*/
public int atoi (String str) {
// write code here
int idx = 0;
int sign = 1;
int val = 0;
// 1. 空字符串
if (str.length() == 0) return 0;
// 2. 忽略前置空
while (str.charAt(idx) == ' ') idx++;
// 3. 记录符号
if (str.charAt(idx) == '-') {sign = -1; idx++;}
if (str.charAt(idx) == '+') idx++;
for (; idx < str.length(); idx++) {
// 4. 处理非法符合
if (str.charAt(idx) > '9') break;
// 5. 处理溢出
if (val > Integer.MAX_VALUE / 10 || //乘上 10 以后就会超出最大范围
//乘上 10 以后没有超出最大范围,但是个位数比最大值的个位数大
(val == Integer.MAX_VALUE / 10 && Integer.MAX_VALUE % 10 < str.charAt(idx) - '0')) {
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
val = val * 10 + str.charAt(idx) - '0';
}
return val * sign;
}
}
京公网安备 11010502036488号