Skip to content
Advertisement

Reverse an integer in JavaScript

I have written the following code to reverse an integer in JavaScript. It works fine but returns a 0 when given an input of -900000. Does anyone know what could be wrong?

/**
 * @param {number} x
 * @return {number}
 */
var reverse = function(x) {
    var negative_number= false;
    var k;
    var new_string;
    if(x<0){
        negative_number = true;
        x=Math.abs(x);
    }
    var n = x.toString(); // convert from number to string
        // Step 1. Use the split() method to return a new array
    var splitString = n.split(""); // var splitString = "hello".split("");
    // ["h", "e", "l", "l", "o"]
    if (negative_number)
    {
        for (var i=0; i< splitString.length-1; i++)
        {
            splitString[i]=splitString[i+1];
        }
    }
    // Step 2. Use the reverse() method to reverse the new created array
    var reverseArray = splitString.reverse(); // var reverseArray = ["h", "e", "l", "l", "o"].reverse();
    // ["o", "l", "l", "e", "h"]

    // Step 3. Use the join() method to join all elements of the array into a string
    var joinArray = reverseArray.join(""); // var joinArray = ["o", "l", "l", "e", "h"].join("");
    // "olleh"
    //return joinArray;
    var number = Number(joinArray);
    if (negative_number)
        number= -Math.abs(number);
    //Step 4. Return the reversed string
    return number;
};

Advertisement

Answer

You don’t need to slice off the - sign from negative numbers, you’ve already taken the absolute value as x. Drop that loop that moves digits around and destroys your values.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement