Search This Blog

2024/03/29

Javascript Interview Question:Reverse Number

Given a signed 32-bit integer x, return x with its digits reversed. If reversing
x causes the value to go outside the signed 32-bit integer range
[-231, 231 - 1], then return 0.

Assume the environment does not allow you to store 64-bit integers
(signed or unsigned).


Example 1:

Input: x = 123
Output: 321
Example 2:

Input: x = -123
Output: -321
Example 3:

Input: x = 120
Output: 21

Constraints:
-2**31 <= x <= 2**31 - 1

Solution(converting number to string then reverse):
let x = -123;
var reverse = function (x) {
let reversedAbs= Math.sign(x) * parseInt(Math.abs(x).toString().split('').reverse().join(''))
return ( -1 * 2 ** 31 > reversedAbs || 2 ** 31 - 1 < reversedAbs) ? 0:reversedAbs
};
let reversedAbs = reverse(x);
console.log(reversedAbs);
Output:
-321

Solution(using maths modulo operator):
let x = -123;

var reverse = function (x) {
let y = Math.abs(x);
let reversedAbs = 0;
let lowerBound = -1 * 2 ** 31;
let upperBound = 2 ** 31 - 1;

while (y > 0) {
reversedAbs = reversedAbs * 10 + (y % 10);
if (lowerBound > reversedAbs || upperBound < reversedAbs) {
return 0;
}
y = Math.floor(y / 10);
}
reversedAbs = Math.sign(x) * reversedAbs;

if (lowerBound > reversedAbs || upperBound < reversedAbs) {
return 0;
} else {
return reversedAbs;
}
};
let reversedAbs = reverse(x);
console.log(reversedAbs);
Output:
-321

No comments:

Post a Comment