昨天小米面试,一个女大神把我带进去的,刚开始以为是HR,随便聊了几分钟,突然问我技术问题,把我也是吓了一跳。第一个问题是手写代码实现String转Int,不能使用IntegerPrase方法。思考了一下想起来使用ASCII值进行比对,也就是‘A-Z’和‘1-9’都有自己的ASCII。主要判断字符串里面的char是不是‘0’,‘9’之间的。当时只顾考虑这个了,没有考虑边界值,数字越界(int 为2的32次方),字符串是不是为空,,是不是含有正负符号,是不是包含非0-9之间的char等细节问题。不要和面试官争执,讨论一个多线程相关的关键词,我的理解错了,然后打电话问HR另一个面试安排,HR问我是不是和面试官发生冲突了,突然感觉很莫名其妙,唉,一面就PASS。
/**
* Created by lang on 17/8/2.
*/
public class Test {
public static void main(String[] arg) {
int test = str2Integer("35241");
}
public static int str2Integer(String str) {
int index = 0;
// 标记是正数还是负数
int sign = 1;
int total = 0;
char ch;
if (str.trim().length() == 0) {
return 0;
}
// 判断正负
if (str.charAt(index) == '+' || str.charAt(index) == '-') {
if (str.charAt(index) == '+')
sign = 1;
else {
sign = -1;
}
index++;
}
while (index < str.length()) {
ch = str.charAt(index);
if (ch < '0' || ch > '9')
break;
if (Integer.MAX_VALUE / 10 < total || Integer.MAX_VALUE / 10 ==
total && Integer.MAX_VALUE % 10 < (ch - '0'))
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
total = total * 10 + (ch - '0');
index++;
}
return sign * total;
}
}