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

题目:把字符串转换成整数


思路:

此题比较麻烦的点是特殊情况较多,需要考虑完全。
1.如果字符串前后有空格,要去除;
2.如果是空串或null,要特殊处理;
3.如果头部有多个正负号,要特殊处理;
4.如果数值超出int的范围,要特殊处理;比int的最大值还要大,已经上溢,这肯定不能通过数字的大小比较,所以需要在字符串的状态下判断是否上溢或下溢。
5.遇到非数字的字符,则转换停止;
刚刚发现一个新的情况未做处理,在数字之前有多个0,如果0之后的数字有溢出情况,而前面的0又没有去处,这种溢出就不会被捕获,还缺这个情况的判断。这种思路真心不好,一条主线是转换成整数,中间穿插出很多特殊情况的分支,感觉就像在打补丁。

基于以上思路,java参考代码如下:

package chapter7;

public class StringToInt {
//    atoi的需求是这样的:
//    如果前面有空格,需要剔除空格;
//    剔除空格后,第一个字符串如果是+号,认为是正数;如果是-号,认为是负数;
//    后面的字符如果不是数字,那么返回0,如果是数字,返回实际的数字。遇到不是数字的字符,转换结束。
//    此外,要考虑空串问题,数值溢出问题[2^(-31) ~ 2^31-1]。

    public static int strToInt(String str) throws Exception{
        if(str==null || str.length()==0)
            throw new Exception("待转换字符串为null或空串");
        String MAX_INT_PLUS_1 = Integer.toString(Integer.MIN_VALUE).substring(1);//
        StringBuilder stringBuilder = new StringBuilder(str.trim());//Stiing.trim()---返回字符串的副本,其中该副本忽略前导空白和尾部空白。
        int flag = 0; //记录无符号的正(2)正(1),负(-1),初始值(0)
        if(stringBuilder.charAt(0)=='-')
            flag = -1;
        else if(stringBuilder.charAt(0)=='+')
            flag = 1;
        else if(stringBuilder.charAt(0)>='0'&&stringBuilder.charAt(0)<='9')
            flag = 2;
        else
            return 0;
        int endIndex = 1;//一共有多少位0~9之间的数字
        while (endIndex<stringBuilder.length()&&stringBuilder.charAt(endIndex)>='0'&&stringBuilder.charAt(endIndex)<='9')
            endIndex++;
        if(flag==2){
            if(stringBuilder.substring(0,endIndex).toString().compareTo(MAX_INT_PLUS_1)>=0)
                throw new Exception("数值上溢,待转换字符串为"+str);
            return Integer.parseInt(stringBuilder.substring(0,endIndex));
        }
        else{
            if(flag==1&&stringBuilder.substring(1,endIndex).compareTo(MAX_INT_PLUS_1)>=0)
                throw new Exception("数值上溢,待转换字符串为"+str);
            if(flag==-1&&stringBuilder.substring(1,endIndex).compareTo(MAX_INT_PLUS_1)>0)
                throw new Exception("数值下溢,待转换字符串为"+str);
            if(flag==-1&&stringBuilder.substring(1,endIndex).compareTo(MAX_INT_PLUS_1)==0)
                //此处注意,此种情况不能用绝对值*(-1),该绝对值已经超出正数的最大值
                return Integer.MIN_VALUE;
            return flag*Integer.parseInt(stringBuilder.substring(1,endIndex));
        }
    }

    public static void funcTest(){
        try {
            System.out.println(strToInt(" 100")); //100
            System.out.println(strToInt("-100")); //-100
            System.out.println(strToInt("0")); //0
            System.out.println(strToInt("-0"));//0
            System.out.println(strToInt("1.23"));  //1
            System.out.println(strToInt("-1.23")); //-1
            System.out.println(strToInt(".123"));  //0
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
    public static void edgeTest(){
        try {
            System.out.println(strToInt("2147483647"));  //2147483647
        }
        catch (Exception e){
            System.out.println(e.getMessage());
        }
        try {
            System.out.println(strToInt("-2147483647")); //-2147483647
        }
        catch (Exception e){
            System.out.println(e.getMessage());
        }
        try {
            System.out.println(strToInt("2147483647"));  //2147483647
        }
        catch (Exception e){
            System.out.println(e.getMessage());
        }
        try {
            System.out.println(strToInt("2147483648"));  //上溢
        }
        catch (Exception e){
            System.out.println(e.getMessage());
        }
        try {
            System.out.println(strToInt("-2147483648")); //-2147483648
        }
        catch (Exception e){
            System.out.println(e.getMessage());
        }
        try {
            System.out.println(strToInt("-2147483649")); //下溢
        }
        catch (Exception e){
            System.out.println(e.getMessage());
        }
        try {
            System.out.println(strToInt(null)); //待转换字符串为null或空串
        }
        catch (Exception e){
            System.out.println(e.getMessage());
        }
        try {
            System.out.println(strToInt(""));   //待转换字符串为null或空串
        }
        catch (Exception e){
            System.out.println(e.getMessage());
        }
    }
    public static void main(String[] args){
        funcTest();
        edgeTest();
    }
}

另一种实现简单功能的java参考代码如下:

package chapter7;

public class StringToInt {
    public static int StrToInt(String str) {
        if(str.length() == 0)//注意点1:特殊输入的测试
            return 0;
        str=str.trim();//用于忽略前后的空白
        int flag = 0;
        if(str.charAt(0) == '+')
            flag = 1;
        else if(str.charAt(0) == '-')
            flag = 2;
        int start = flag > 0 ? 1 : 0;
        long res = 0;//用long型防止溢出//注意点2:一般在需要用到res变量的时候才声明,不要声明在最前面。
        while(start < str.length()){
            if(str.charAt(start) > '9' || str.charAt(start) < '0')
                return 0;
            res = res * 10 + (str.charAt(start) - '0');
            start ++;
        }
        return flag == 2 ? -(int)res : (int)res;//注意点3:返回值类型需要符合规范
    }
    public static void main(String[] args){
        System.out.println(StrToInt(" 100")); //100
        System.out.println(StrToInt("-100")); //-100
    }
}

注意点在代码注解中。

测试用例:

a.功能测试(输入的字符串表示正数、负数和0)。
b.边界值测试(最大的正数;最小的负数)。
c.特殊输入测试(输入的字符串为nullptr指针;输入的字符串为空字符串;输入的字符串中有非数字字符等)。

参考:

https://www.jianshu.com/p/31dc58b9eca9
https://yq.aliyun.com/articles/642752

猜你喜欢

转载自blog.csdn.net/qq_43502142/article/details/88036291