https://leetcode-cn.com/problems/string-to-integer-atoi/submissions/
public class _8_字符串转换整数 {public int myAtoi(String s) {if (s == null || s.equals("")) {return 0;}s = removeHeadZero(s.trim());if (s == null || s.equals("")) {return 0;}char[] str = s.toCharArray();if (!isValid(str)) {return 0;}// str 是符合日常书写的,正经整数形式// posi 是否是 非负数boolean posi = str[0] == '-' ? false : true;int minq = Integer.MIN_VALUE / 10;int minr = Integer.MIN_VALUE % 10;int res = 0;int cur = 0;// 先一律转成负数来做, 因为负数比正数多一个for (int i = (str[0] == '-' || str[0] == '+') ? 1 : 0; i < str.length; i++) {cur = '0' - str[i];if ((res < minq) || (res == minq) && cur < minr) {return posi ? Integer.MAX_VALUE : Integer.MIN_VALUE;}res = res * 10 + cur;}if (posi && res == Integer.MIN_VALUE) {return Integer.MAX_VALUE;}return posi ? -res : res;}private String removeHeadZero(String str) {boolean r = (str.startsWith("+") || str.startsWith("-"));int s = r ? 1 : 0;for (; s < str.length(); s++) {if (str.charAt(s) != '0') {break;}}// s 到了第一个不是'0'字符的位置int e = -1;// 左<-右for (int i = str.length() - 1; i >= (r ? 1 : 0); i--) {if (str.charAt(i) < '0' || str.charAt(i) > '9') {e = i;}}// e 到了最左的 不是数字字符的位置return (r ? String.valueOf(str.charAt(0)) : "") + str.substring(s, e == -1 ? str.length() : e);}private boolean isValid(char[] chars) {if (chars[0] != '-' && chars[0] != '+' && (chars[0] < '0' || chars[0] > '9')) {return false;}if ((chars[0] == '-' || chars[0] == '+') && chars.length == 1) {return false;}return true;}}
- 这道题就是细节扣,没什么算法
