美文网首页
7.Reverse Integer

7.Reverse Integer

作者: 一棵会开花的树_f654 | 来源:发表于2018-01-20 11:25 被阅读0次

问题描述:
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 hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

需要注意的问题:

整数溢出 Integer.MAX_VALUE和Integer.MIN_VALUE
之前理解错了,以为要判断输入的数是否溢出,之后才意识到需要判断的是被翻转后的数字是否溢出

此题有较多解法:
方法一:
一开始的做法是用long保存结果(这样就不会溢出了),最后判断long的值是否在Integer.MAX_VALUE和Integer.MIN_VALUE之间,但最后输出结果的时候需要进行类型转换,将long转换成int

   public int reverse(int x) {
        long number = 0;
        while(x != 0){
            number = number*10 + x%10;
            x /= 10;
        }
        if(number>Integer.MAX_VALUE || number<Integer.MIN_VALUE) return 0;
        return (int)number;
    }

方法二:

  public int reverse(int x) {
        int res = 0;
        while (x != 0) {
            if (abs(res) >Integer.MAX_VALUE / 10) return 0;
            res = res * 10 + x % 10;
            x /= 10;
        }
        return res;
    }

此种解法摘自http://www.cnblogs.com/grandyang/p/4125588.html
据说是官方答案。在贴出答案的同时,OJ还提了一个问题 To check for overflow/underflow, we could check if ret > 214748364 or ret < –214748364 before multiplying by 10. On the other hand, we do not need to check if ret == 214748364, why? (214748364 即为 INT_MAX / 10)

为什么不用check是否等于214748364呢,因为输入的x也是一个整型数,所以x的范围也应该在 -2147483648~2147483647 之间,那么x的第一位只能是1或者2,翻转之后res的最后一位只能是1或2,所以res只能是 2147483641 或 2147483642 都在int的范围内。但是它们对应的x为 1463847412 和 2463847412,后者超出了数值范围。所以当过程中res等于 214748364 时, 输入的x只能为 1463847412, 翻转后的结果为 2147483641,都在正确的范围内,所以不用check。

方法三:
这种方法是方法二的变形,如果溢出了,除以10的结果就跟之前不一样了

  public int reverse(int x) {
        int res = 0;
        while (x != 0) {
            int t = res*10 + x%10;
            if (t / 10 != res) return 0;
            res = t;
            x /= 10;
        }
        return res;
    }

相关文章

网友评论

      本文标题:7.Reverse Integer

      本文链接:https://www.haomeiwen.com/subject/jawzoxtx.html