leetcode: 8. String to Integer (atoi)
阿新 • • 發佈:2018-12-28
Difficulty
Medium
Description
/**
* Example 1:
* Input: "42"
* Output: 42
*
* Example 2:
* Input: " -42"
* Output: -42
* Explanation: The first non-whitespace character is '-', which is the minus sign.
* Then take as many numerical digits as possible, which gets 42.
*
* Example 3:
* Input: "4193 with words"
* Output: 4193
* Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.
*
* Example 4:
* Input: "words and 987"
* Output: 0
* Explanation: The first non-whitespace character is 'w', which is not a numerical
* digit or a +/- sign. Therefore no valid conversion could be performed.
*
* Example 5:
* Input: "-91283472332"
* Output: -2147483648
* Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
* Therefore INT_MIN (−231) is returned.
*
*/
Solution
class Solution {
public int myAtoi(String str) {
int i = 0;
int ret = 0;
int sign= 1;
int digit;
if (str == null)
return 0;
str = str.trim();
if (str.length() == 0)
return 0;
if (str.charAt(0) == '+') {sign = 1; i++;}
if (str.charAt(0) == '-') {sign = -1; i++;}
while (str.length() > i) {
if (!Character.isDigit(str.charAt(i)))
return (int)ret*sign;
digit = str.charAt(i) - '0';
if (ret > (Integer.MAX_VALUE - digit) / 10 || (ret == Integer.MAX_VALUE / 10 && digit > 7))
return sign == 1 ? Integer.MAX_VALUE : Integer. MIN_VALUE; //檢查是否越界
ret = ret * 10 + digit;
i++;
}
return (int)ret*sign;
}
}