String to Integer (atoi)
Description
Example
"10" => 10
"-1" => -1
"123123123123123" => 2147483647
"1.0" => 1public 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;
}
}Last updated