The title

Title link: leetcode-cn.com/leetbook/re…


Answer key


1. Convert to a character array and then invert it

To do integer inversion, we may not know how to do it, but we do know how to do array inversion, so we can do the following steps:

  • Convert an integer to a string;
  • Cut each bit of the string into an array;
  • Invert the array; (String inversion via array inversion)
  • Merge arrays into strings; (Check the merged string using maxStr and minStr)
  • Convert strings to numbers;

Computers can store only 32-bit signed integers, and return 0 when the number is reversed beyond the storage range. So we need to check the string in the penultimate step to determine whether the integer corresponding to the string is out of the storage range;

/ * * *@param {number} x
 * @return {number}* /
var reverse = function(x) {

    let str = String(x);
    let arr = str.split(' ');
    let isMinus = false;
    // maxStr and minStr are used to limit the output to 0 if the number reverses beyond both;
    let maxStr = (Math.pow(2.31) - 1).toString();
    let minStr = (0 - Math.pow(2.31)).toString();

    
    if(The '-' === arr[0]) {
        arr.shift();
        isMinus = true;
    }

    // Swap arrays
    let head = 0,
        rear = arr.length - 1;

    while(head < rear) {

        arr[head] -= arr[rear];
        arr[rear] = Number(arr[rear]) + arr[head];
        arr[head] = arr[rear] - arr[head];
        head++;
        rear--;
    }


    //
    if(isMinus) {
        arr.unshift(The '-');
        str = arr.join(' ');

        if(str.length === minStr.length && str > minStr) {
            return 0 ;
        }
        return Number(str);

    }else{
        str = arr.join(' ');
        if(str.length === maxStr.length && str > maxStr){
            return 0;
        }
        return Number(str); }};Copy the code


2. Think further

If you don’t have an environment that doesn’t allow you to store 64-bit integers, you can invert them numerically instead of converting them to arrays.

/ * * *@param {number} x
 * @return {number}* /
var reverse = function(x) {

    let num = Math.abs(x),
        result = 0;
    const MAX_VALUE = Math.pow(2.31) - 1,
        MIN_VALUE = 0 - Math.pow(2.31)

    while(0! == num) { result = result *10 + num % 10;

        num = ( num / 10) | 0;
        
    }


    if(x < 0) {
        result = (0 - result);
    }
    
    if(result > MAX_VALUE || result < MIN_VALUE) {
        return 0;
    }
    return result;
     
};
Copy the code


If you have a better way of thinking and reconciliation, welcome to discuss ah ~


Juejin. Cn/post / 700669…