Leetcode07.整数反转 给你一个 32 位的有符号整数 x ,返回 x 中每位上的数字反转后的结果。 如果反转后整数超过 32 位的有符号整数的范围 [−231,  231 − 1] ,就返

一、题目

给你一个 32 位的有符号整数 x ,返回 x 中每位上的数字反转后的结果。

如果反转后整数超过 32 位的有符号整数的范围 [-2 147 483 648,2 147 483 647] ,就返回 0。

假设环境不允许存储 64 位整数(有符号或无符号)。

示例 1:

输入:x = 123 输出:321

示例 2:

输入:x = -123 输出:-321

示 例 3:

输入:x = 120 输出:21 示例 4:

输入:x = 0 输出:0

提示:
-2 147 483 648 <= x <= 2 147 483 647

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-integer
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

二、代码

主要解决的问题为整型越界问题

class Solution {
    public int reverse(int x) {
	if(x==0)return x;
	int a1=x;
	int n=0;//多少位
	int b=0;
	int[] a2=new int[10];
	while(a1!=0) {
		a2[n++]=a1%10;
		a1/=10;
		if(n==9&&a1!=0) {
		 if(Math.abs(a2[0])>2){return 0;}
            else if(Math.abs(a2[0])<2)continue;
            else if(Math.abs(a2[1])>1){return 0;}
               else if(Math.abs(a2[1])<1)continue;
            	else if(Math.abs(a2[2])>4){return 0;}
                   else if(Math.abs(a2[2])<4)continue;
                	else if(Math.abs(a2[3])>7){return 0;}
                     else if(Math.abs(a2[3])<7)continue;
                    	else if(Math.abs(a2[4])>4){return 0;}
                        else if(Math.abs(a2[4])<4)continue;
                        	else if(Math.abs(a2[5])>8){return 0;}
                            else if(Math.abs(a2[5])<8)continue;
                            	else if(Math.abs(a2[6])>3){return 0;}
                                else if(Math.abs(a2[6])<3)continue;
                                			else if(Math.abs(a2[7])>6){return 0;}  
                                            else if(Math.abs(a2[7])<6)continue;
             if(Math.abs(a2[8])>4)
				{return 0;}
                else if(Math.abs(a2[8])<4)continue;
            else{
                if(a1>0){
                if(a1>7)return 0;}
                else if(a1<-8)
                return 0;
            }
		}
	}

	while(x%10==0) {
		x/=10;
		n--;
	}
    while(x!=0) {
    	b+=Math.pow(10, n-1)*(x%10);
    	x/=10;
    	n--;
    }
  return b;
    }
}

结果:
在这里插入图片描述

三、代码优化

我们发现代码中有大量的if else,所以必然是需要进行优化的

class Solution {
    public int reverse(int x) {
	int res=0;
	while(x!=0) {
		int pop=x%10;
		x/=10;
		if(res>Integer.MAX_VALUE/10||(res==Integer.MAX_VALUE/10&&pop>7))return 0;
		if(res<Integer.MIN_VALUE/10||(res==Integer.MIN_VALUE/10&&pop<-8))return 0;
		res=res*10+pop;
	}
	return res;
    }
}
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值