Solution in javascript


  • 0
    H

    Question

    Reverse digits of an integer.
    
    Example1: x = 123, return 321
    Example2: x = -123, return -321
    
    click to show spoilers.
    
    Note:
    The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
    

    Solution

    Algorithm
    we use mathematical operation, such as %, /, to get every number, and push them into a new array. After that, array -> string -> int.

    The pseudocode is as following:

    • Initialize symbol of the reversed integer. the symbol of positive number can be omitted.
    • get the absolute value of x.
    • create a new array itemArr to store the numbers of x.
    • Initialize itemArr[0] and itemArr[len - 1] .
    itemArr[0] = Math.floor(x / Math.pow(10, len - 1));
    itemArr[len - 1] = x % 10;
    
    • Loop through the length of x until get every number of x except the highest digit and the lowest order digit.

      • itemArr[i] = Math.floor((x % Math.pow(10, len - i)) / Math.pow(10, len - i - 1));
    • Loop itemArr reversely to get the string of the reversed integer.

    • covert the string into int. if the reversed integer > Math.pow(2, 32 - 1), return 0, else return the reversed integer.

    Javascript

    var reverse = function(x) {
        
        var res = x >= 0 ? '' : '-';
        x = Math.abs(x);
        
        var len = x.toString().length;
        var itemArr = [];
        itemArr[0] = Math.floor(x / Math.pow(10, len - 1));
        itemArr[len - 1] = x % 10;
        
        for (var i = 1; i < len - 1; i ++) { 
            itemArr[i] = Math.floor((x % Math.pow(10, len - i)) / Math.pow(10, len - i - 1));
        }
        
        for (var i = len - 1; i >= 0; i --) {
            res += itemArr[i];  
        }    
        
        res = res * 1;
         if (Math.abs(res) > Math.pow(2, 32 - 1)) {
            return 0;
        }
        
        return res;
    };
    

    Complexity Analysis

    • Time complexity: O(2len). len is the digit of x.

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.