写在前面:
本人小白,刷LeetCode,练习算法和写程序的感觉,在此做简单记录。若有不当之处,欢迎留言交流。
/**
* LeetCode 0008 字符串转换整数atoi
* author: MammothKan
* time: 2020/4/29
* 题目描述:https://leetcode-cn.com/problems/string-to-integer-atoi/
* 解题思路:
* 1. 去除字符串的前部空白字符
* 2. 判断首字符为“+”、“-”、数字 或 其它字符,并给出对应的plusMinus和startIndex
* 3. 遍历字符串result = result*10 + digit,直到遇到非数字字符结束
* 4. int边界问题,要求每次运算都满足Integer.MAX_VALUE > result*10 + digit。
* 正向思维中,先计算result,再判断大小,但是在程序中当result*10 + digit溢出时,便会报错。
* 采用逆向思维,Integer.MAX_VALUE > result*10 + digit 可以转会为 (Integer.MAX_VALUE - digit) / 10 > result 依此来判断。
*/
public class L0008字符串转换整数atoi {
public int myAtoi(String s) {
if (s.length() == 0) {
return 0;
}
//1. 去除字符串的前部空白字符
s = s.trim();
char[] cArray = s.toCharArray();
char firstChar = cArray[0];
boolean plusMinus;
int startIndex;
//2. 判断首字符为“+”、“-”、数字 或 其它字符,并给出对应的plusMinus和startIndex
if (firstChar == '-'){
plusMinus = false;
startIndex = 1;
}
else if (firstChar == '+'){
plusMinus = true;
startIndex = 1;
}
else if (Character.isDigit(firstChar)) {
plusMinus = true;
startIndex = 0;
}
else {
return 0;
}
//3. 遍历字符串result = result*10 + digit,直到遇到非数字字符结束
int result = 0;
for (int i=startIndex; i<cArray.length; i++) {
if (Character.isDigit(cArray[i])) {
int digit = cArray[i]-'0';
//4. 溢出处理
int resultMax = (Integer.MAX_VALUE - digit) / 10;
if (resultMax < result) {
return plusMinus ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
else {
result = result*10 + digit;
}
}
else {
break;
}
}
return plusMinus ? result : -1*result;
}
public static void main(String[] args) {
System.out.println(new L0008字符串转换整数atoi().myAtoi("fsd 42"));
}
}