【LeetCode】7. Reverse Integer

Difficulty: Easy

 More:【目录】LeetCode Java实现html

Description

https://leetcode.com/problems/reverse-integer/java

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

Example 1:post

Input: 123
Output: 321

Example 2:ui

Input: -123
Output: -321

Example 3:this

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.code

Intuition

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

Solution

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

    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的结果将会 和以前不一致)ip

    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实现

相关文章
相关标签/搜索