思路:
题目没有什么难的,就是把string转换成integer。
需要注意的是有些坑,首先要去头尾的空格,其次+-号只能有一个,如果中间出现不是数字的情况,直接截断数字。String的值如果比integer的极限还大(小)的时候,返回极值就可以,所以推荐用long去接收这个数字,然后再判断边界。
其实用integer接收数字也行,只要除以10,然后再判断尾数就可以,但是性能上的差距可以忽略不计,所以此处并没有给自己找麻烦。
public int myAtoi(String str) { //前后去空 str = str.trim(); if (str.isEmpty()) return 0; long num = 0; int index = 0; int positive = 1; //判断正负 if (str.charAt(0) == '+' || str.charAt(0) == '-') { if (str.charAt(index) == '-') positive = -1; index++; } while (index < str.length() && str.charAt(index) >= '0' && str.charAt(index) <= '9') { num = num * 10 + (str.charAt(index) - '0'); if (num > Integer.MAX_VALUE) { return positive == -1 ? Integer.MIN_VALUE : Integer.MAX_VALUE; } index++; } return (int) (positive * num); }