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.
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.
本题需要解决的问题是将字符串数字转化为整型数据,其中包括几点小问题:
1.字符串合法性问题;
2.字符串长度为零处理;
3.字符串中+与-号;
4.数据范围溢出问题。
public class Solution {
public int AtoiTest(String str) {
long result= 0;
int max=Integer.MAX_VALUE;
int min=Integer.MIN_VALUE;
int sign = 1;
int index = 0;
if(str == null) {
return 0;
}
str = str.trim();
if (str.length() == 0) {
return 0;
}
if (str.charAt(index) == '+') {
index++;
} else if (str.charAt(index) == '-') {
sign = -1;
index++;
}
for (; index < str.length(); index++) {
if (str.charAt(index) < '0' || str.charAt(index) > '9')
break;
result = result* 10 + (str.charAt(index) - '0');
if (num > max) {
break;
}
}
if (num * sign >= max) {
return max;
}
if (num * sign <= min) {
return min;
}
return (int)result * sign;
}
}