8. String to Integer (atoi)
题目的原意是 实现atoi 的方法来将String转换成数值。
方法的基本要求: 先去除第一个字母前的空格,然后判断第一个字母看是否是+,-,数字。如果是+给个+符号并且将光标移到下一个字母,如果是-, 给个-符号并且将光标移到下一个字母。 如果是数字,需要将数字的Strng格式的部分转换成数值。
例子:
Input: "42"
Output:42
Input: " -42"
output: -42
Input: "4193 with words"
Output: 4193
Input: "words and 987"
Output: 0
Input: "-91283472332"
Output:-2147483648
public class Solution {
private static final int maxDiv10 = Integer.MAX_VALUE / 10;
public int myAtoi(String str) {
int i = 0;
int n = str.length();
//move index to the non space character
while (i < n && Character.isWhitespace(str.charAt(i))) {
i++;
}
//use sign to identify + / - for the number
int sign = 1;
//if + do move the index to next, if - give sign = 1 and move the index to next
if (i < n && str.charAt(i) == '+') {
i++;
} else if (i < n && str.charAt(i) == '-') {
sign = -1;
i++;
}
//now start to setup number
int num = 0;
while(i < n && Character.isDigit(str.charAt(i))) {
//convert character into digit number by Character.getNumericValue()
int digit = Character.getNumericValue(str.charAt(i));
//the condition to have num = num*10 + digit is going to be
//num < Integer.MAX_VALUE, so in the last digit to add in
//num < maxDiv10, digit num should <= 8
//in other words, if num > maxDiv10 we can use sign value to choose Integer.MIN_VALUE or Integer.MAX_VALUE
//also if num == maxDiv10, we need consider the value of last digit. if digit >= 8, if sign == 1, return Integer.MAX_VALUE.
//if digit == -1, return Integer.MIN_VALUE.
if (num > maxDiv10 || num == maxDiv10 && digit >= 8) {
return sign == -1 ? Integer.MIN_VALUE : Integer.MAX_VALUE;
}
//if we pass the last step or we don't have these overflow case, we can add the last digit into num
num = num * 10 + digit;
//for each step we need move the index for one big
i++;
}
//after get +/- and the integer value. we can get the final value
return sign * num;
}
}
解法二:
public int myAtoi(String str) {
if (str == null || str.length() == 0) {
return 0;
}
str = str.trim();
int sign = 1;
int start = 0;
int len = str.length();
long sum = 0;
if (str.charAt(start) == '+') {
start++;
} else if (str.charAt(start) == '-') {
sign = -1;
start++;
}
for (int i = start; i < len; i++) {
if (!Character.isDigit(str.charAt(i))) {
return (int) sum * sign;
}
sum = sum * 10 + (str.charAt(i) - '0');
if (sign == 1 && sum > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
if (sign == -1 && sign * sum < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
}
return (int) sum * sign;
}