leetcode-7 ReverseInteger

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

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

由题意很简单的推出:将数字反转,但提示中有说道 反转后的数字 如果是超过了 int的最大值或是最小值 则返回0,这里我们可以利用long进行返回 然后long转int,long的位数比int大,只需判断long的结果是否大于或小于int的最大最小值即可最终代码如下:

    public int reverse(int x) {
       long result = 0;
       int tmp = x;
       if(x<0) {
           tmp = -x;
       }
        while(tmp>0) {
            result=result*10+(tmp%10);
            tmp=tmp/10;
        }
        if(result>Integer.MAX_VALUE || result<Integer.MIN_VALUE) {
            return 0;
        }
        return x<0? -(int)result:(int)result;
        
    }

猜你喜欢

转载自blog.csdn.net/qq_38340127/article/details/89224896