Write a function reverse(x)
that takes a 32-bit signed integer and returns its digits reversed.
If the reversed value overflows the 32-bit integer range, return 0
.
0
if the reversed number exceeds the range of a 32-bit signed integer.O(d)
where d
= number of digits.O(1)
— only a few extra variables.Input | Output | Explanation |
---|---|---|
123 | 321 | Digits reversed normally. |
-123 | -321 | Sign preserved, digits reversed. |
1534236469 | 0 | Overflow occurs after reversal. |
xCopy
to remember its original sign.Math.abs(x)
(or abs(x)
in other languages) to simplify digit extraction.rev = 0
.x != 0
:
last = x % 10
rev
: rev = rev * 10 + last
x = Math.floor(x / 10)
rev
exceeds the 32-bit signed integer limit.0
.xCopy
) was negative, return -rev
; otherwise, return rev
.Let’s trace x = 123
Step | x | last | rev (after step) |
---|---|---|---|
Start | 123 | - | 0 |
1 | 12 | 3 | 3 |
2 | 1 | 2 | 32 |
3 | 0 | 1 | 321 |
Output → 321
Now for x = -123
We take the absolute value → 123
Reverse it → 321
Then reapply the sign → -321
var reverse = function(x) {
// Preserve the Original Number
let xCopy = x;
let rev = 0;
// Work with Absolute Value
x = Math.abs(x);
// Reverse the Digits
while (x > 0) {
let last = x % 10;
rev = rev * 10 + last;
x = Math.floor(x / 10);
}
// Overflow check
if (rev > 2**31 - 1) return 0;
// Restore sign
return xCopy < 0 ? -rev : rev;
};
console.log(reverse(123)); // 321
console.log(reverse(-123)); // -321
console.log(reverse(1534236469)); // 0 (overflow)
I'm Rahul, Sr. Software Engineer (SDE II) and passionate content creator. Sharing my expertise in software development to assist learners.
More about me