zoukankan      html  css  js  c++  java
  • LeetCode之Easy篇 ——(7)Reverse Integer

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

    思路:

      1、是否考虑正负号?

        通过调用java.lang.Math类中取绝对值的abs方法,四种情况:

    static double abs(double a);//返回 double 值的绝对值。
    static float abs(float a);//返回 float 值的绝对值。
    static int abs(int a);//返回 int 值的绝对值。
    static long abs(long a);//返回 long 值的绝对值。

      2、32位int型数据范围? 

         最小值:Integer.MIN_VALUE:-2147483648

         最大值:Integer.MAX_VALUE:2147483647

      3、代码第6行为什么只需跟214748364(记为num)比较?

        首先,只有当输入值为十位数,末尾数字记为a(第一位必定是1或者2,因为输入值也必须在最大值与最小值之间,否则报错),res跟num才显得有意义,尽管之前也一直在比较。

        为了方便叙述,下面的res都是指最后一次跟 num比较的情况。

        a为0时,res是8位数,肯定小于num。最后输出9位数,肯定不会越界。

        a为1时,res是以1开头的9位数,肯定小于num。最后输出10位数,也不会越界。

        a为2时,res是以24开头的9位数,肯定大于num,不必进行也不能进行下一次赋值,因为再加一位肯定超过范围,而且也没有跟num比较,return 0的机会了,因为此时x的值为0,直接跳出循环,return res,结果肯定报错,因为超过最大值。

        a大于2时,res肯定大于num,直接return 0即可,理由同上。

      4、怎么表示输出值? 

        res = res * 10 + x % 10;完美解决了输入值尾数为0的情况。

    Java代码如下:

    import static java.lang.Math.abs;
    class Solution {
        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;
        }
    }
  • 相关阅读:
    立方体
    file 图片预览
    [LeetCode][JavaScript]Single Number III
    [LeetCode][JavaScript]Longest Substring Without Repeating Characters
    [LeetCode][JavaScript]Missing Number
    [LeetCode][JavaScript]Course Schedule II
    [LeetCode][JavaScript]Course Schedule
    [LeetCode][JavaScript]Ugly Number II
    [LeetCode][JavaScript]Ugly Number
    [LeetCode][JavaScript]Single Number II
  • 原文地址:https://www.cnblogs.com/promiseslc/p/8585627.html
Copyright © 2011-2022 走看看