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.

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jun 7, 2019 at 20:47
\$\endgroup\$
2

1 Answer 1

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.

answered Jun 7, 2019 at 22:20
\$\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\$ Commented Jun 8, 2019 at 22:43
  • \$\begingroup\$ I don't understand, the question said we are guaranteed to receive a signed 32 bit integer. \$\endgroup\$ Commented Jun 9, 2019 at 4:25

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.