[LeetCode] 7. Reverse Integer
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Example 1:
Input: x = 123
Output: 321
Example 2:
Input: x = -123
Output: -321
Example 3:
Input: x = 120
Output: 21
Constraints:
-231 <= x <= 231 - 1
整数反转。
给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。
如果反转后整数超过 32 位的有符号整数的范围 [−231, 231 − 1] ,就返回 0。
假设环境不允许存储 64 位整数(有符号或无符号)。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/reverse-integer
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
这个题可以配合跟第九题一起做,思路是一样的。
跑一个例子吧,比如把 123 反转成 321。我们需要不断拿到 input 数字的最低位,加到结果 res 中,然后把 res 乘以 10,并将 input 除以 10,直到把 input 遍历成 0 为止。
复杂度
时间O(n) - input 数字的长度
空间O(1)
代码
Java实现
class Solution {
public int reverse(int x) {
long res = 0;
int n = x;
while (n != 0) {
res = res * 10 + n % 10;
if (res >= Integer.MAX_VALUE || res <= Integer.MIN_VALUE) {
return 0;
}
n /= 10;
}
return (int) res;
}
}
JavaScript实现
/**
* @param {number} x
* @return {number}
*/
var reverse = function (x) {
const max = Math.pow(2, 31);
let res = 0;
while (x !== 0) {
res = res * 10 + (x % 10);
if (res > max || res < -max) {
return 0;
}
x = parseInt(x / 10);
}
return res;
};
相关题目
7. Reverse Integer
9. Palindrome Number
2108. Find First Palindromic String in the Array