整数反转(reverse)

1.数学方法:
·没有数组和堆栈的帮助下使用数学方法:
从ans * 10 + pop > MAX_VALUE这个溢出条件来看
·当出现 ans > MAX_VALUE / 10 且 还有pop需要添加 时,则一定溢出
·当出现 ans == MAX_VALUE / 10 且 pop > 7 时,则一定溢出,7是2^31 - 1的个位数
从ans * 10 + pop < MIN_VALUE这个溢出条件来看
·当出现 ans < MIN_VALUE / 10 且 还有pop需要添加 时,则一定溢出
·当出现 ans == MIN_VALUE / 10 且 pop < -8 时,则一定溢出,8是-2^31的个位数
在这里插入图片描述


public class Solution {
    public int reverse(int x){
        int ans=0;//初始化颠倒后的整数
        while(x!=0){
            int pop=x%10;//获取X的最后一位
            //判断ans是否溢出
            if (ans>Integer.MAX_VALUE/10||(ans==Integer.MAX_VALUE/10&&pop==7))//ans=ans*10+pop溢出,ans*10+pop>MAX_VALUE
                return 0;
            if (ans<Integer.MIN_VALUE/10||(ans==Integer.MIN_VALUE/10&&pop<-8))
                return 0;
            ans=ans*10+pop; //颠倒后的X
            x/=10;  //除去X的最后一位
        }
        return ans;
    }

    public static void main(String[] args) {
        int x=0;
        Solution a=new Solution();
        System.out.println(a.reverse(x));

    }
}
    pop operation 弹出操作,上托操作 从堆栈顶部取出数据元素的操作。出栈操作
    push operation    推送操作,进栈操作,压栈操作

2.字符串与trycatch:

public class Solution_str {
    public int reverse(int x){
        int y=x;
        if (y<0)
            y*=(-1);
        String str=String.valueOf(y);//String.valueOf方法,将其他类型的数据转换为String类型
       char[] temp= str.toCharArray();//toCharArray方法:将字符串转换为字符数组
        str="";//初始化str
        for (int i=temp.length-1;i>=0;i--){
            str+=temp[i];
        }
        try {
            int result=Integer.parseInt(str);//Integer.parseInt()方法,将()里的类型转换为整数;
            if (result<0){
                return result*(-1);
            }else {
                return result;
            }


        }catch (Exception e){
                return 0;
        }
    }

    public static void main(String[] args) {
        int x=123456;
        Solution_str str=new Solution_str();
        System.out.println(str.reverse(x));
    }
}

复习(学习)常用方法:
String.valueOf方法,将其他类型的数据转换为String类型
toCharArray方法:将字符串转换为字符数组
Integer.parseInt()方法,将()里的类型转换为整数;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值