String to Integer (atoi)
str trim 并且trim 后检查是不是length == 0
check 不是数字的时候 返回当前的结果乘以sign
Description
Implement function atoi
to convert a string to an integer.
If no valid conversion could be performed, a zero value is returned.
If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.Have you met this question in a real interview? Yes
Example
"10" => 10
"-1" => -1
"123123123123123" => 2147483647
"1.0" => 1
public class Solution {
/**
* @param str: A string
* @return: An integer
*/
public int atoi(String str) {
// write your code here
if(str == null ) return 0;
str = str.trim();
if(str.length() == 0) return 0;
int sign = 1, index = 0;
if(str.charAt(index) == '+'){
index++;
}else if(str.charAt(index) == '-'){
sign = -1;
index++;
}
long num = 0;
for (;index < str.length() ;index++ ){
//not num
if(str.charAt(index) < '0' || str.charAt(index) > '9'){
break;
}
num = num * 10 + (str.charAt(index) -'0');
if(num > Integer.MAX_VALUE){
break;
}
}
if(num * sign < Integer.MIN_VALUE){
return Integer.MIN_VALUE;
}
if(num * sign > Integer.MAX_VALUE){
return Integer.MAX_VALUE;
}
return (int)num*sign;
}
}
二刷 时间复杂度 o(n), space o(1)
class Solution {
public int myAtoi(String str) {
//corner case " + -" not valid . out bounday
if(str == null || str.length() == 0)
return 0;
str = str.trim();
if(str.length() == 0){
return 0;
}
int sign = 1, start = 0;
long res = 0;
char f = str.charAt(0);
if(f == '+'){
sign =1;
start++;
}
if(f == '-'){
sign = -1;
start++;
}
for(int i = start; i< str.length() ; i++){
if(!Character.isDigit(str.charAt(i))){
return (int) res*sign;
}
res = res*10 + str.charAt(i) - '0';
if(res > Integer.MAX_VALUE){
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
}
return (int) res*sign;
}
}
Last updated