1、题目描述
【JZ49】将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0。
知识点:字符串,边界考察
难度:☆☆
2、解题思路
本题的出题给的函数返回值是 int 类型,在 Java 中,int 占了 4 个字节,以最高位为符号位计算,那么 int 可以表示的数字范围是 [-231, 231-1] 。当超出了 int 所能表示的数字区间,我们也要把它当成不合法的数值,返回 0,否则本题无法做下去。
初始:long result = 0L; long intMax = 2147483647L; boolean isPositive = true
定义一个函数int charToInt(char ch);
判断输入的字符是否属于 ‘0’~‘9’,是则返回字符对应的数字,否则返回0。
开始遍历字符串的每一个字符,第一个字符允许三种情况:
1、’+’,isPositive = true;
2、’-’ ,isPositive = flase;
3、‘0’~‘9’,result = result * 10 + (0~9)
从第二个字符开始,只能是 ‘0’~‘9’,否则直接返回 0;
遍历完毕后,检查 reuslt 是否超出了int 类型所能表示的范围,是则返回 0 ,否则把 result 转为 int 类型返回。
3、解题代码
package pers.klb.jzoffer.hard;
/**
* @program: JzOffer2021
* @description: 把字符串转换成整数
* @author: Meumax
* @create: 2020-07-23 10:21
**/
public class StrToInt {
public int StrToInt(String str) {
int length = str.length();
if (length == 0) return 0;
int chNum = -1;
long result = 0L; // 用 long 来装载字符串转成的数值
long intMax = 2147483647L; // int 类型所能表示的最大正数,最小负数为
boolean isPositive = true; // 是正数
for (int i = 0; i < length; i++) {
if (i == 0 && str.charAt(i) == '+') continue;
if (i == 0 && str.charAt(i) == '-') {
isPositive = false;
continue;
}
chNum = charToInt(str.charAt(i));
if (chNum == -1) return 0;
result = result * 10 + chNum;
}
// 判断是否超出 int 的范围
if ((isPositive && result > intMax) || (!isPositive && -result < (-intMax - 1))) {
return 0;
} else {
return isPositive ? (int) result : (int) -result;
}
}
private int charToInt(char ch) {
switch (ch) {
case '0':
return 0;
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
default:
return -1;
}
}
}
4、解题心得
本题考查的重点不在字符比对,而是对边界的判断,凡是类似返回某种数值的,一定要注意方法的返回类型有没有可能超出数值的表示区间。