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

Constraints:

  • -231 <= x <= 231 - 1

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/*
* @Description: 7. Reverse Integer
* @Author: libk
* @Github: https://github.com/libk
*/
/**
* @param {number} x
* @return {number}
*/
const reverse = function (x) {
let res = 0
while (x !== 0) {
let rem = x % 10
x = ~~(x / 10) // 连续两次按位取反,将小数部分舍去
res = res * 10 + rem
if (res > Math.pow(2, 31) - 1 || res < Math.pow(-2, 31)) {
return 0
}
}
return res
}