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.
一刷:
测试:
- "+-2"
- " 123 456"
- " -11919730356x"
- "2147483647"
- "-2147483648"
- "2147483648"
- "-2147483649"
- "+2"
这题的难点在于所有的corner case, 面试时碰到要仔细和面试官多交流
- 判断str是否为空或者长度是否为0
- 处理前后的space,也可以用str = str.trim();
- 尝试求出符号sign
- 处理数字
(1) 假如char c = str.charAt(index)是数字,则定义int num = c - '0', 接下来判断是否越界
1). 当前 res > Integer.MAX_VALUE / 10,越界,根据sign 返回 Integer.MAX_VALUE或者 Integer.MIN_VALUE
2). res == Integer.MAX_VALUE / 10时, 根据最后sign和最后一位数字来决定是否越界,返回Integer.MAX_VALUE或者 Integer.MIN_VALUE
3). 不越界情况下,res = res * 10 + num - 处理非数字和‘+’, ‘-’,直接跳到6.
- 返回结果 res * sign
public class Solution {
public int myAtoi(String str) {
int res = 0;
if(str == null || str.length() == 0) return res;
int neg = 1, digit;
for(int i=0; i<str.length(); i++){
str = str.trim();
if(str.charAt(i)=='-' && i == 0) neg = -1;
else if(str.charAt(i)=='+' && i == 0) neg = 1;
else if(str.charAt(i)<'0' || str.charAt(i)>'9') return neg*res;
else{
digit = str.charAt(i) - '0';
int overflow = overflow(res, digit, neg);
if(overflow>0 ) return Integer.MAX_VALUE;
else if(overflow<0) return Integer.MIN_VALUE;
res = res*10 + digit;
}
}
return res*neg;
}
private int overflow(int res, int digit, int sign){
if(sign > 0){
if(res>Integer.MAX_VALUE/10) return 1;
else if(res == Integer.MAX_VALUE/10 && digit > 7) return 1;
}
else{
if(res>Integer.MAX_VALUE/10) return -1;
else if(res == Integer.MAX_VALUE/10 && digit > 8) return -1;
}
return 0;
}
}