【LeetCode】7. Reverse Integer

Difficulty: Easy

 More:【目录】LeetCode Java实现

Description

https://leetcode.com/problems/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.

Intuition

这道题要注意几个情况:1.题目要求只能用int类型;2. 要考虑到负数的情况;3.考虑前后为0的情况,例如00100翻转后为1,而不是100;4. 考虑到翻转后的数字越界的情况,即要注意answer>Integer.MAX_VALUE或者answer<Integer.MIN_VALUE的情况。

Solution

解法一:(乘以10之前,绝对值与Integer.MAX_VALUE/10比较)

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

  

解法二:(越界的情况下,ans/10的结果将会 和之前不一致)

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

  

What I've learned

  1. 利用ans=ans*10+x%10进行翻转。

  2. 本题思考时必须要注意到正负数的情况。利用ans=ans*10+x%10进行翻转时,则不用区分正负,因为负数%10的结果也还是负数。 

  3. 一定要注意溢出的情况,解法一在乘以10之前,用绝对值与Integer.MAX_VALUE/10比较;而解法二是根据溢出后的结果/10与之前不一致来判断。两种方法都要好好记住。

  4. 解法一中,为什么不用判断Math.abs(ans)==Integer.MAX_VALUE/10的情况?

    原因是,方法接收的参数x也为int类型,其最高位只能是1或者2,所以Integer.MAX_VALUE/10+1或者2都不会超出Integer.MAX_VALUE的范围。

  5. Integer.MAX_VALUE=0x7FFF FFFF=2^31-1=2147483647;Integer.MIN_VALUE=0x8000 0000=-2^31=-2147483648.

  6. 上面的边界值,最高位为2,最低位为7和8。一共10位数字。

 

 More:【目录】LeetCode Java实现

 

posted @ 2018-12-20 21:21  华仔要长胖  阅读(303)  评论(0编辑  收藏  举报