Reverse Integer
Question
Given a 32-bit signed integer, reverse digits of an integer.
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Examples
Input : 123 Output: 321
Input: -123 Output: -321
Input: 120 Output: 21
Lets think about that
- You have basically have a lower bound and upper bound number that you can play with or you have to reverse;
- The lower bound is the smallest value that would round up to the estimated value. The upper bound is the smallest value that would round up to the next estimated value.
/**
* Reverse Integer
* @param {number} x - 32-bit signed Integer
* @returns {number} reversed integer
*/
export function ReverseInteger(x: number): number {
if (x < 0) return -1 * ReverseInteger(-x);
const solution = parseInt((x + '').split('').reverse().join(''));
console.log('solution', solution);
return solution > 2 ** 31 - 1 ? 0 : solution;
}
console.log('ReverseInteger', ReverseInteger(123));
/**
* "123"
* [1,2,3]
* [3,2,1]
* Result => 321
*/