zoukankan      html  css  js  c++  java
  • [LeetCode] 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 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.

    整数反转。

    这个题可以配合跟第九题一起做,思路是一样的。

    时间O(n)

    空间O(1)

    JavaScript实现

    跑一个例子吧,比如把123反转成321。排除corner case为0的情况以外,需要不断拿到这个数字的最低位,加到结果res中,然后乘以10,直到把input遍历成0为止。

    123,第9行r = 0 + 3 = 3,13行x = 12

    第9行r = 3 * 10 + (12 % 10) = 32,13行x = 1

    第9行r = 32 * 10 + (1 % 10) = 321,13行x = 0

    跳出while循环,得到321.

    注意越界问题,其他的应该比较直观。关键代码在第9行。我判断是否超出Integer范围的方式比较笨,参见第6行。

     1 /**
     2  * @param {number} x
     3  * @return {number}
     4  */
     5 var reverse = function (x) {
     6     const max = Math.pow(2, 31);
     7     let res = 0;
     8     while (x !== 0) {
     9         res = res * 10 + (x % 10);
    10         if (res > max || res < -max) return 0;
    11         x = parseInt(x / 10);
    12     }
    13     return res;
    14 };

    Java实现

     1 class Solution {
     2     public int reverse(int x) {
     3         long res = 0;
     4         while (x != 0) {
     5             res = res * 10 + x % 10;
     6             x /= 10;
     7             if (res > Integer.MAX_VALUE || res < Integer.MIN_VALUE) {
     8                 return 0;
     9             }
    10         }
    11         return (int) res;
    12     }
    13 }

    LeetCode 题目总结

  • 相关阅读:
    笔试题 1.3 百度 2012 10.09 简答题 + 程设 --A
    windows中搜索dll的顺序
    笔试题 1.2 关于大文件处理:
    笔试题 1.1 最少比赛数目
    小优化
    LightOJ
    LightOJ
    LightOJ
    LightOJ
    LightOJ
  • 原文地址:https://www.cnblogs.com/cnoodle/p/11639138.html
Copyright © 2011-2022 走看看