算法习题篇之ReverseInteger

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.

给你一个32位的整数,求他的相反位置的数 ,注意,假设我们的环境只能储存三十二维以内的整数,如果超出了这个范围,则返回零。

接下来就是我的垃圾代码了:

思路很简单,用了上一篇大神的方法,然后增加了一些修改:

class Solution {
    public int reverse(int x) {
           int z = java.lang.Math.abs(x);
            int y = 0;
        try{
            while(z>0){
                 if(y>=214748365||(y>214748364&&z%10!=1)) {
        		 return 0;
        	 }
                y = y*10+z%10;
                z/=10;
            }
                if(x<0){
                  return y*-1; 
                }
                return y;    
    }catch(Exception e){
        return 0;
    }
}
}

根据上一篇我们很简单的就能求出一个数的相反位的数,但是这个相反的数不能超出位数限制,则需要判断,(y>214748364&&z%10!=1)对于这个判断大家可能会有疑惑,但是这是根据事实来的原数也是一个不能超出限制的数,所以只需要判断z的第一位是不是1就可以了。

大神的干货好像 也不是干货了,怪不得赞比差评少

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

不过学到的地方还是边界值的运用吧,像我就只能2147483647,明明就是一个Integer.MAX_VALUE解决的问题,好像不用去拿绝对值,然后在整些有的没的啊,负数就是负的,行吧,ok。还是我的判断更简单一些,他的更严谨,但是我的更合乎常理。

class Solution {
    public int reverse(int x) {     
        int numRev;
        try {
            numRev = Integer.parseInt((new StringBuilder(Integer.toString(Math.abs(x)))).reverse().toString());
        } catch (NumberFormatException e) {
            return 0;
        }
        return (x < 0) ? (-1)*numRev : numRev;
    }
}

原来StringBuilder 有个这么霸道的函数啊,reverse直接倒转啊,蛮强的吗,然后感觉有点眼前一亮,毕竟想用转化字符串的方式写,但是感觉我想的要麻烦多了,毕竟我并不知道这个函数,呵呵。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值