7. 整数反转 中等 拆分整数的每一位 判断是否溢出 取余

  1. 整数反转
    给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。

如果反转后整数超过 32 位的有符号整数的范围 [−231, 231 − 1] ,就返回 0。

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

示例 1:

输入:x = 123
输出:321
示例 2:

输入:x = -123
输出:-321
示例 3:

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

输入:x = 0
输出:0

提示:

-231 <= x <= 231 - 1

提示

判断溢出时,如果当前位小于MAX的当前位,那后面不用比了,肯定不会溢出

class Solution {
    public int reverse(int x) {
    	int p=0,a[]=new int[10];
    	int ma[]=new int[]{2,1,4,7,4,8,3,6,4,7};
    	int mi[]=new int[]{2,1,4,7,4,8,3,6,4,8};
    	boolean fu=false,over=false;
    	if(x<0)fu=true;
    	while(x!=0){
    		a[p++]=Math.abs(x%10);
    		x/=10;
    	}
    	if(p==10){
    		for(int i=0;i<p;++i){
                if(a[i]<ma[i])break;
    			if(fu==false&&a[i]>ma[i]||fu&&a[i]>mi[i])return 0;
    		}
    	}
    	int ans=0;
    	for(int i=0;i<p;++i){
    		ans*=10;
    		ans+=a[i];
    	}
    	if(fu)ans=-ans;
    	return ans;
    }
}
class Solution {
    public int reverse(int x) {
    	int t=0;
    	while(x!=0){
            if(t<Integer.MIN_VALUE/10||t>Integer.MAX_VALUE/10)return 0;
    		t*=10;
    		t+=x%10;
    		x/=10;
    	}
    	return t;
    }
}
posted @ 2022-11-17 23:01  林动  阅读(3)  评论(0编辑  收藏  举报