2
\$\begingroup\$

Problem Description:

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

Example 1:

  • Input: 123
  • Output: 321

Example 2:

  • Input: -123

  • Output: -321

Example 3:

  • Input: 120

  • Output: 21

Note: It should return zero when it reaches out of limit [−2 ^31, 2 ^31 − 1]

My implementation

var reverse = function (x) {
  var minRange = Math.pow(-2, 31)
  var maxRange = Math.pow(2, 31) - 1

  var isNegative = false;
  if (x < 0) {
    isNegative = true;
    x = (x - x - x);
  }
  var result = Number(x.toString().split('').reverse().join(''));
  (isNegative) ? result = (result - result - result) : result;
  if (result < minRange || result > maxRange) {
    return 0
  } else {
    return result;
  }

};

Please help to improve.

\$\endgroup\$
2
3
\$\begingroup\$

-- adding this as an answer because I can't comment.

The answer referenced in ggorlen's comment, can be improved by remarking that a (negative number % 10) is a negative number, so there is no need for sign checking.

const reverse = val => {
    let res = 0;
    const Base = 10;
    while (val) {
        res = res * Base + (val % Base);
        val = (val / Base) | 0;
    }
    return (res | 0) == res ? res : 0;
}

Tests:

reverse(1) === 1; 
reverse(-1) === -1 
reverse(0) === 0 
reverse(Math.pow(2,31) - 1) === 0 
reverse(Math.pow(-2,31)) === 0 
reverse(1463847412) === 2147483641
reverse(1463847413) === 0 

By the way, what's the reasoning behind "x = (x - x - x)"? x-x evaluates to zero. so that's just x = - x.

\$\endgroup\$
2
  • \$\begingroup\$ +1 Welcome to CR. You can skip the sign but I will point out that numbers are converted to int in a standard way, ignoring the sign will only work for integers in range. Outside the range and you return the wrong value because to do not account for the correct conversion. Eg (new Int32Array([21474836481]))[0] === 1 yet you reverse it to reverse(21474836481) === 1536152588 \$\endgroup\$
    – Blindman67
    Jun 8 '19 at 22:43
  • \$\begingroup\$ I don't understand, the question said we are guaranteed to receive a signed 32 bit integer. \$\endgroup\$
    – Slei.
    Jun 9 '19 at 4:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.