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;
    }
}

猜你喜欢

转载自blog.csdn.net/m0_51801058/article/details/114017464