您的位置:首页 > 职场人生

【剑指offer】面试题67:把字符串转换成整数

2017-08-11 14:09 411 查看

题目

将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。

数值为0或者字符串不是一个合法的数值则返回0

思路

其实思路很简单,但是要考虑的非法输入和边界值条件很多

合法的输入:1.数字 2.符号(+-)+ 数字

非法输入:

1.null

2.字符串为空

3.字符串只有一个符号(+-)

4.字符串中带有非数字字符

5.字符串超过int能表示的范围

代码

public class _67_StringToInt {

public boolean isValid = false;

public int StrToInt(String str) {
if(str == null || str.trim().equals("")) {
return 0;
}
int index = 0;
long result = 0;
boolean isPositive = true;
if(str.charAt(0) == '+' || str.charAt(0) == '-') {
++index;
// 字符串中只有正负号
if(index == str.length())
return 0;
if(str.charAt(0) == '-')
isPositive = false;
}

for(int i = index; i < str.length(); ++i) {
if(str.charAt(i) < '0' || str.charAt(i) > '9') {
return 0;
}
result *= 10;
result += (str.charAt(i) - '0') * (isPositive ? 1 : -1);
if(result > Integer.MAX_VALUE || result < Integer.MIN_VALUE)
return 0;
}
isValid = true;
return (int) result;
}
}


测试

public class _67_Test {

public static void main(String[] args) {
test1();
test2();
test3();
}

/**
* 功能测试
* 1.带符号(+-)
* 2.不带符号
*/
private static void test1() {
_67_StringToInt sti = new _67_StringToInt();
int result = sti.StrToInt("666");
MyTest.equal(result, 666);
MyTest.equal(true, sti.isValid);

result = sti.StrToInt("+666");
MyTest.equal(result, 666);
MyTest.equal(true, sti.isValid);

result = sti.StrToInt("-666");
MyTest.equal(result, -666);
MyTest.equal(true, sti.isValid);
}

/**
* 边界测试
* 1.0
* 2.Integer.MAX_VALUE
* 3.Integer.MIN_VALUE
*/
private static void test2() {
_67_StringToInt sti = new _67_StringToInt();
int result = sti.StrToInt("0");
MyTest.equal(result, 0);
MyTest.equal(true, sti.isValid);

result = sti.StrToInt(String.valueOf(Integer.MAX_VALUE));
MyTest.equal(result, Integer.MAX_VALUE);
MyTest.equal(true, sti.isValid);

result = sti.StrToInt(String.valueOf(Integer.MIN_VALUE));
MyTest.equal(result, Integer.MIN_VALUE);
MyTest.equal(true, sti.isValid);
}

/**
* 极端测试
* 1.null
* 2.空字符串
* 3.超过int表示范围
* 4.只带符号
* 5.非法表示
*/
private static void test3() {
_67_StringToInt sti = new _67_StringToInt();
int result = sti.StrToInt(null);
MyTest.equal(result, 0);
MyTest.equal(false, sti.isValid);

result = sti.StrToInt("");
MyTest.equal(result, 0);
MyTest.equal(false, sti.isValid);

result = sti.StrToInt("1436468468422");
MyTest.equal(result, 0);
MyTest.equal(false, sti.isValid);

result = sti.StrToInt("+");
MyTest.equal(result, 0);
MyTest.equal(false, sti.isValid);

result = sti.StrToInt("-");
MyTest.equal(result, 0);
MyTest.equal(false, sti.isValid);

result = sti.StrToInt("123a86");
MyTest.equal(result, 0);
MyTest.equal(false, sti.isValid);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: