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.
-
1\$\begingroup\$ Check out codereview.stackexchange.com/questions/220274 \$\endgroup\$ggorlen– ggorlen2019年06月07日 21:21:43 +00:00Commented Jun 7, 2019 at 21:21
-
\$\begingroup\$ Check this out - leetcode.com/problems/reverse-integer/solution, it might help you. \$\endgroup\$Justin– Justin2019年06月08日 09:07:16 +00:00Commented Jun 8, 2019 at 9:07
1 Answer 1
-- 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.
-
\$\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 toreverse(21474836481) === 1536152588
\$\endgroup\$Blindman67– Blindman672019年06月08日 22:43:01 +00:00Commented 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\$Slei.– Slei.2019年06月09日 04:25:17 +00:00Commented Jun 9, 2019 at 4:25