LeetCode:7. 整数反转

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Naux1/article/details/89211753

给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。

示例 1:

输入: 123
输出: 321

 示例 2:

输入: -123
输出: -321

示例 3:

输入: 120
输出: 21

注意:

假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231,  231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。

class Solution {
    public int reverse(int x) {
        int[] a=new int[20];
		int num=0,n=x;;
		int newx=0;
		int flag;
		if(x>=0) flag=1;	
		else flag=0;
				
		while(n!=0){
			a[num]=n%10;
			n=n/10;
			num++;
		}

		for(int i=0;i<num;i++){
			if(flag==1){
				if (newx>Integer.MAX_VALUE/10 || (newx == Integer.MAX_VALUE / 10 && a[i]> 7)) 
				 return 0;
			}
			if(flag==0){
				 if (newx<Integer.MIN_VALUE/10 || (newx == Integer.MIN_VALUE / 10 && 0-a[i] < -8)) 
	        	 return 0;
			}
	        
			
			newx=newx*10+a[i];
		}
		return newx;
    }
}

2^31-1=2147483647

-2^31=-2147483648 

为了便于解释,我们假设是正数。

  1. 如果newx = newx⋅10+a[i] 导致溢出,那么一定有newx ≥ Integer.MAX_VALUE/10。
  2. 如果 newx > Integer.MAX_VALUE/10​,那么newx = newx⋅10+a[i] 一定会溢出。
  3. 如果 newx = Integer.MAX_VALUE/10​,那么只要a[i] > 7,newx = newx⋅10+a[i] 就会溢出。

猜你喜欢

转载自blog.csdn.net/Naux1/article/details/89211753
今日推荐