https://leetcode.com/problems/string-to-integer-atoi/
这个题实现String to Integer的转换,规则较多,没太多的算法层面的东西,就是按照题目的规则去实现就行了。要注意有很多corner case,需要有很多的判断。
实现代码和注释如下:
public int myAtoi(String s) {
long res = 0, len = s.length();
boolean flag = false; // 是否为负数
if (len == 0) return 0;
char[] ch = s.toCharArray();
int i = 0;
// 去掉leading space
while(i < len && ch[i] == ' ') i++;
// 判断开始的是否为-/+或者数字
if (i < len && (ch[i] > '9' || ch[i] < '0') && (ch[i] != '-' && ch[i] != '+')) return 0;
// 判断是否为符号
if (i < len && ch[i] == '-') {
flag = true;
i++;
} else if (i < len && ch[i] == '+') i++;
// 判断数字和是否有leading 0
while (i < len && ch[i] == '0') i++;
//计算值
while (i < len && ch[i] <= '9' && ch[i] >= '0') {
res = res * 10 + (ch[i] - '0');
if (res > Integer.MAX_VALUE || res < Integer.MIN_VALUE) break;
i++;
}
// 判断符号
if (flag) res = (-1) * res;
// 处理最大值和最小值
return res > Integer.MAX_VALUE ? Integer.MAX_VALUE : (res < Integer.MIN_VALUE ? Integer.MIN_VALUE : (int)res);
}