Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
/**
*
* Created by ustc-lezg on 16/4/6.
*/
public class Solution {
public int myAtoi(String str) {
//去除空白字符
str = str.trim();
if (str.isEmpty()) {
return 0;
}
long res = 0;
int sign = 1;
int i = 0;
boolean flag = false;
//判断是否有 '-' , '+'标志
if (str.charAt(i) == '-') {
sign = -1;
flag = true;
}
if (str.charAt(i) == '+') {
sign = 1;
flag = true;
}
if (flag) {
++i;
}
for (int len = str.length(); i < len; i++) {
int num = str.charAt(i) - '0';
if (num < 0 || num > 9) {
break;
}
res = res * 10 + num;
if (res > Integer.MAX_VALUE || res < Integer.MIN_VALUE) {
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
}
return (int)(sign * res);
}
}