leecode 7整数反转

整数反转

题目

在这里插入图片描述

解法一

class Solution {
    public int reverse(int x) {
        int rev=0;
        while(x!=0){
            int pop=x%10;//最低位
            x=x/10;//最高位
            //MAX_VALUE : 2147483647 MIN_VALUE : -2147483648
            if(rev>Integer.MAX_VALUE/10||(rev==Integer.MAX_VALUE/10&&pop>7))
                return 0;
            if(rev<Integer.MIN_VALUE/10||(rev==Integer.MIN_VALUE/10&&pop<-8))
                return 0;
            rev=rev*10+pop;
        }
        return rev;
    }
}

解法二

class Solution {
    public int reverse(int x) {
        String s=Integer.toString(Math.abs(x));//取绝对值
        s=reverse(s);递归反转
        if(x<0){
            try{
                x=Integer.parseInt("-"+s);//将字符串转换为整型异常抛出return 0
            }catch(Exception e){
                return 0;
            }
        }else{
            try{
                x=Integer.parseInt(s);
            }catch(Exception e){
                return 0;
            }
        }
        return x;
    }
    public String reverse(String str){
        if(str==null||str.equals("")){
            return str;
        }
        return str.charAt(str.length()-1)+reverse(str.substring(0,str.length()-1));
    }
}

猜你喜欢

转载自blog.csdn.net/YangYanDong666/article/details/88778206