Skip to content

Instantly share code, notes, and snippets.

@AlanD20
Last active April 2, 2022 15:01
Show Gist options
  • Save AlanD20/d3abfb2303ce6f3027b536226ab97899 to your computer and use it in GitHub Desktop.
Save AlanD20/d3abfb2303ce6f3027b536226ab97899 to your computer and use it in GitHub Desktop.
Reverse integer - typescript - 80ms/100ms
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