一、题目描述
二、我的解题
- 挺简单的一个题目(我觉得),但最后还是属实给我整崩溃了,我对越界的问题是真的不好解决 。
class Solution { public int myAtoi(String s) { boolean plus = true; boolean first=true; int res=0; for (int i=0;i<s.length();i++){ String s1= String.valueOf(s.charAt(i)); System.out.println(res); if (s1.equals("-")){ plus=false; } if (s1.equals(".")){ break; } if (s1.equals(" ")){ if (first){ continue; }else break; } try { res=res*10+ Integer.parseInt(s1); first=false; } catch (Exception e) { if ((s1.equals("-") || s1.equals("+"))&& first){ first=false; }else return plus?res:-res; } if (res > Integer.MAX_VALUE / 10) { return plus?Integer.MAX_VALUE:-Integer.MAX_VALUE-1; } if (res < Integer.MIN_VALUE / 10) { return plus?Integer.MAX_VALUE:-Integer.MAX_VALUE-1; } } return plus?res:-res; } }
- 我人快杀了实在是改不动了
- 力扣在细节测试上真的强,不过有点转牛角尖了,我只能自愧不如。
三、参考改进
public class Solution { public int myAtoi(String str) { int len = str.length(); char[] charArray = str.toCharArray(); //去空格 int index = 0; while (index < len && charArray[index] == ' ') { index++; } if (index == len) { return 0; } //如果出现符号字符,仅第 1 个有效,并记录正负 int sign = 1; char firstChar = charArray[index]; if (firstChar == '+') { index++; } else if (firstChar == '-') { index++; sign = -1; } //将后续出现的数字字符进行转换 // 不能使用 long 类型,这是题目说的 int res = 0; while (index < len) { char currChar = charArray[index]; if (currChar > '9' || currChar < '0') { break; } // 判断乘以 10 以后是否越界 if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && (currChar - '0') > Integer.MAX_VALUE % 10)) { return Integer.MAX_VALUE; } if (res < Integer.MIN_VALUE / 10 || (res == Integer.MIN_VALUE / 10 && (currChar - '0') > -(Integer.MIN_VALUE % 10))) { return Integer.MIN_VALUE; } res = res * 10 + sign * (currChar - '0'); index++; } return res; } }
- 这样写更好判断越界,思路清晰多了
复杂度分析:时间复杂度:O(N) 空间复杂度:O(1)