Last active
April 2, 2022 15:01
-
-
Save AlanD20/d3abfb2303ce6f3027b536226ab97899 to your computer and use it in GitHub Desktop.
Reverse integer - typescript - 80ms/100ms
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function reverse(x: number): number { | |
const nums: string[] = [...(x.toString())]; | |
const list: number[] = []; | |
const negative: boolean = nums[0] == '-' ? true : false; | |
if (negative) nums[0] = "\0"; | |
nums.reverse().map(digit => { | |
if (digit == "\0") return; | |
list.push(Number(digit)); | |
}) | |
const result = Number(negative ? '-' + list.join('') : list.join('')); | |
if (result > 2 ** 31 || result < -(2 ** 31)) return 0; | |
else return result; | |
} | |
console.log(reverse(-123456)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment