7. Reverse Integer

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.

 

本菜鸟:

class Solution {
    public int reverse(int x) {
       int[] a = new int[10];
        int wei = 1;
        int flag = 0;
        if(x==-2147483648) return 0;
     if(x<0) {x = -x; flag = 1;}
     for(int i = 0;i < 10 ;i++){
         a[i] = x%10;
         x = x/10;
         if(x>0) wei++;
     }
     x = 0;
    for(int j = 0;j < wei;j++) {
        if(x < Integer.MAX_VALUE/10 ||x == Integer.MAX_VALUE/10) x = x*10+a[j];
        else  return 0;
   }
        if(flag==0) return x; else return -x;
    }
}

这道LeetCode上面简单题的前几题,考查的内容却是相当的多。这个问题本身很简单。

难点1:-2^31 *(-1)= ?

经过测试,结果为-2^31。如果按照上述代码的写法,必须要考虑这种情况。

难点2:

在生成x的reverse的时候,要考虑数值是否越界的问题。

 

大神的代码:

@author LyneDefense
class Solution {
    public int reverse(int x) {
     int res = 0;
        int temp = 0;
        while(x != 0){
            int tail = x%10;
            temp = res*10 +tail;
            if((temp-tail)/10 !=res) //判断res是否溢出
                return 0;
            res = temp;
            x = x/10;
        }
        return res;
    }
}

这里面通过(temp-tail/10 )==res来判断temp是否溢出,实在是一种非常高明的手段,普通人估计也不敢这么写。数据溢出以后,程序并不会报错,只是结果不对而已。并且,可以看出,按照正负号分类实在是我们一厢情愿而已。

 

官方代码:

class Solution {
    public int reverse(int x) {
        int rev = 0;
        while (x != 0) {
            int pop = x % 10;
            x /= 10;
            if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
            if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
            rev = rev * 10 + pop;
        }
        return rev;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值