每日一题-字符串 leetcode7

209 阅读2分钟

一、题目描述

二、题目思路

  1. 正数,且不以0结尾,如123
  2. 负数,如-123
  3. 以0、00、0...0结尾的正数或负数,如1200,-230
  4. 题目提示需要注意int溢出问题,因此应该在反转后对数字进行判断,防止溢出

对于1、2、3三种情况,1忽略,思路是可以首先将整数转换为字符串,从尾遍历读取非零(解决3)字节,然后如果读取后字符串结尾是 '-' ,则去除 '-' (解决2),最后转换为int类型

转换为int类型存在一个问题,即IntegerparseInt(String s) 函数,最大转换范围为-2^31 -- 2^31-1

解决办法是使用try{} catch(){}语句

三、提交代码

class Solution {
    public int reverse(int x) {
        int result =0;
        StringBuilder stringBuilder = new StringBuilder();
        String str = String.valueOf(x);
        for(int i =str.length()-1;i>=0;i--){
            if(str.charAt(i) ==0){
                continue;
            }else{
                stringBuilder.append(str.charAt(i));
            }
        }
        if(stringBuilder.charAt(stringBuilder.length()-1)=='-'){
            stringBuilder.deleteCharAt(stringBuilder.length()-1);
            stringBuilder = stringBuilder.insert(0,'-');
        }
        try{
            result = Integer.parseInt(stringBuilder.toString().trim());
        }catch (Exception e){
            result =0;
        }
        return result;
    }
}

四、存在问题

  1. 使用较多库函数
  2. 字符串转换效率低

五、优解代码

class solution{
    public int reverse(int x){
        int result =0;
        int last =0;
        while(x != 0){
            last = x % 10;
            x/=10;
            if( result > Integer.MAX_VALUE/10||(result == Integer.MAX_VALUE/10 && last == 7)){
                return 0;
            }
            if( result < Integer.MIN_VALUE/10||(result == Integer.MIN_VALUE/10 && last ==8)){
                return 0;
            }
            result = result*10 + last;
        }
        return result;
    }
}

六、优解思路

  1. 运用数学计算的方法,取余、整除相结合
  2. 需要注意的问题是溢出问题,不难判断,当result > Integer.MAX_VALUE/10 则不需要继续判断,直接返回0;或者当result == Integer.MAX_VALUE/10last == 7时,同样不需要继续判断,直接返回0
  3. 超出最小值的溢出问题同理,此时 last == 8
  4. Integer.MAX_VALUE = 2^31-1 = 2147483647
  5. Integer.MIN_VALUE = -2^31 = -2147483648

七、代码更正

优解代码更新为

class Solution {
    public int reverse(int x) {
        int result =0;
        int done =0;
        while(x !=0){
            done = x %10;
            x = x/10;
            if (result > Integer.MAX_VALUE /10 || ((result == Integer.MAX_VALUE/10))&&(done > Integer.MAX_VALUE %10) ){
                return 0;
            }else if (result < Integer.MIN_VALUE/10 ||((result == Integer.MIN_VALUE/10)&&(done < Integer.MIN_VALUE %10 ))){
                return 0;
            }
            result = ( result*10 ) + done;
        }
        return result;
    }
}

对于最大值的判断:if (result > Integer.MAX_VALUE /10 || ((result == Integer.MAX_VALUE/10))&&(done > Integer.MAX_VALUE %10) ),或者原来的语句if (result > Integer.MAX_VALUE /10 || ((result == Integer.MAX_VALUE/10))&&(done == 7) )都可以通过

对于本题,只需要判断if (result > Integer.MAX_VALUE /10)同样可以通过,因为题目的输入限制了输入的整数数值,如果用户输入超过最大值,则程序报错

但建议使用更正后的代码,因为可以应对输入字符串的情况