[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 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/11639138.html