Skip to content

Instantly share code, notes, and snippets.

@codediodeio
Created September 4, 2017 23:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codediodeio/617184def4d42dadf602e6cd4a5b2201 to your computer and use it in GitHub Desktop.
Save codediodeio/617184def4d42dadf602e6cd4a5b2201 to your computer and use it in GitHub Desktop.
Reverse integer and determine overflow in JavaScript - LeetCode solution
/**
* @param {number} x
* @return {number}
*/
var reverse = function(x) {
let a = x.toString().split('')
let num;
if(a[0] == '-') {
let c = a.shift()
num = parseInt(c +a.reverse().join(''))
} else {
num = parseInt(a.reverse().join(''))
}
if(Math.abs(num) > Math.pow(2, 31)) {
num = 0;
}
return num
};
@stevieoj
Copy link

Seems to me numbers above Math.pow(2, 31) would overflow.

@uyenntm
Copy link

uyenntm commented Nov 22, 2017

You can use Math.sign(n) to check negative number
function reverseInt(n) {
return Math.sign(n)*parseInt(n.toString().split('').reverse().join(''));
}

@murtaza63
Copy link

var reverse = function(x) {
var myInt = Math.abs(x).toString().split('').reverse().join('');

var num = +myInt
return (x<0 ?  -1:1) * num

};
after submission my code status shows wrong answer on leetcode what is wrong with code please help me!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment