2

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;
};
6
  • 1
    What is the point of this for loop? `for (var i=0; i< splitString.length-1; i++) { splitString[i]=splitString[i+1]; } ??? Commented Jun 27, 2017 at 1:48
  • what are you trying to accomplish exactly. what are you expecting this does? also, passing -1002 gives -2200. Commented Jun 27, 2017 at 1:49
  • @StephenQuan: If its a negative number, I need to remove the negative sign from it. Oh I see I have done that already above. Commented Jun 27, 2017 at 1:50
  • theres no reason to do the loop that @StephenQuan mentions, since you are already absing the input Commented Jun 27, 2017 at 1:50
  • What do you expect it to be? Commented Jun 27, 2017 at 2:39

6 Answers 6

3

Some excellent answers already posted.

I decided to show a slightly different variation:

  • Use 'recursion' to handle the negative case
  • The rest of the function just focus on the positive case
  • Broke each intermediate calculation into its own line

Here's a code snippet with comments illustrating how -123 becomes -321:

function reverse(x) {
  if (x < 0) return -reverse(-x); // reverse(-123) === -reverse(123)
  var str = x.toString(); // "123"
  var strArray = str.split(""); // [ "1", "2", "3" ]
  var revArray = strArray.reverse(); // [ "3", "2", "1" ]
  var rev = revArray.join(""); // "321"
  return Number(rev);
}

console.log(reverse(-123)); // Outputs: -321
console.log(reverse(0)); // Outputs: 0
console.log(reverse(-900000)); // Outputs: -9

Sign up to request clarification or add additional context in comments.

1 Comment

I like the recursion here. That makes it cleaner than the other solutions' Math.sign versions.
2

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.

Comments

2

One thing that's clear is that this is much more complicated than necessary. I think this will do what you want:

const rev = (i) => Math.sign(i) * Number(('' + Math.abs(i)).split('').reverse().join(''))

2 Comments

Thanks Scott. I am actually coming from a PHP background and new to JavaScript. Just learning it while solving the problems. But thanks a lot as I have to work on the load time of these solutions as the next step.
I thought I detected someone new to the language. :-) My point had nothing to do with load time, or strictly with the size of your solution. instead, I just wanted to note that many of the techniques you did manually are already built in. The solution from @StephenQuan actually shows this more effectively.
2

Looks overly complicated. This should be sufficient:

function reverse(n) {  
  return Number(Array.from(String(Math.abs(n))).reverse().join('')) * Math.sign(n);
}

console.log(reverse(144));
console.log(reverse(-90000));

Comments

0

This is my variant, after playing on Leetcode. Conditions:

Given a 32-bit signed integer, reverse digits of an integer.

Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

const reverse = function(x) {
  const revInt = parseFloat(x.toString().split('').reverse().join('')) * Math.sign(x);
  const maxInt = (2 ** 31) - 1;
  const minInt = -(2 ** 31);
  return (revInt >= minInt && revInt <= maxInt) ? revInt : 0;
};

Comments

0

Try this:

function reverse(x) {
        if(x < Math.pow(-2,31) || x > Math.pow(2,31)) return 0;
        let result = 0;
        while(x != 0) {
            let tail = x % 10;            
            let newResult = result * 10 + tail;
            if((newResult - tail) / 10 !== result) {
                return 0;
            }
            result = newResult;            
            x = parseInt(x / 10);
            if(result <  Math.pow(-2,31) || result > Math.pow(2,31) - 1)
            { 
            return 0;
            }     
        }        
        return result;        
    }
    console.log(reverse(-123));//-321
    console.log(reverse(0));//0
    console.log(reverse(123000000000000000000000000000000000000));//0
    console.log(reverse(-90000));//-9
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.