zoukankan      html  css  js  c++  java
  • 【LeetCode】007. 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.

    题解:

       难点在于溢出的判断上。当 abs(res) 大于等于 INT_MAX / 10 时,就需要判断结果是否要溢出了。INT_MIN = -2147483648,INT_MAX = 2147483647。这里为什么不需要在

     1 class Solution {
     2 public:
     3     int reverse(int x) {
     4         int res = 0;
     5         while (x) {
     6             int digit = x % 10;
     7             if (abs(res) > INT_MAX / 10 || res == INT_MAX / 10 && digit > 7 || res == INT_MIN / 10 && digit < -8)
     8                 return 0;
     9             res = res * 10 + digit;
    10             x /= 10;
    11         }
    12         
    13         return res;
    14     }
    15 };

        其实在 abs(res) == INT_MAX / 10 时可以直接做溢出处理,原因是输入 x 是 int 类型,所以 x 的范围也应该在 INT_MIN 和 INT_MAX 之间,那么 x 的第一位只能是1或者2,x 翻转之后 res 的最后一位只能是1或2。当 abs(res) == INT_MAX / 10时,下一步的 res 只能是 (-)2147483641 或 (-)2147483642,对应的 x 为 1463847412 和 2463847412,而2463847412 超出了 int 的数值范围。所以当 res 等于 214748364 时, 输入的 x 只能为 1463847412, 翻转后的结果 res 为 2147483641,在正确的范围内。

      

     1 class Solution {
     2 public:
     3     int reverse(int x) {
     4         int res = 0;
     5         while (x) {
     6             int digit = x % 10;
     7             if (abs(res) > INT_MAX / 10)
     8                 return 0;
     9             res = res * 10 + digit;
    10             x /= 10;
    11         }
    12         
    13         return res;
    14     }
    15 };

    转自:Grandyang

  • 相关阅读:
    Mac环境下svn的使用
    ionic动态切换主题皮肤
    NodeJS中的require和import
    ionic3.x开发小坑记录(一)
    ios微信浏览器中video视频播放问题
    微信内置浏览器在使用video标签时(安卓)默认全屏的原因及解决办法
    转《发布ionic应用到App Store的完整步骤 》
    Tomcat内存问题解决办法
    linux系统的文件保护
    linux系统一些信息(待整理)
  • 原文地址:https://www.cnblogs.com/Atanisi/p/8643537.html
Copyright © 2011-2022 走看看