Last Commit: 2024-01-06 17:50:27

views:

Table of Content

7. Reverse Integer

source: https://leetcode.com/problems/reverse-integer/

Question

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

思路

比较常规的一题。

/**
 * @param {number} x
 * @return {number}
 */
var reverse = function(x) {
    const s = Array.from(`${x}`);
    let minus = false;
    if (s[0] === '-') {
        s.shift();
        minus = true;
    }
    s.reverse();
    const v = Number(s.join(''));
    if (v > 2 ** 31 - 1) return 0;
    return minus ? -v : v;
};