// SOLUTION 1 - MY SOLUTION (RUNTIME - 92MS, MEMORY - 40.7MB) var reverse = function(x) { // set variable that converts integer to a string, splits into an arr, reverses arr, and rejoins into a string const temp = x.toString().split("").reverse().join(""); // converts string back into an integer let reversedNum = parseInt(temp); // using original argument, check if reversed number needs to be a positive or negative value if (Math.sign(x) === -1) reversedNum = reversedNum * -1 // check to see if reversed integer fits within listed 32-bit contraint if (Math.pow(-2, 31) > reversedNum || reversedNum > Math.pow(2, 31)) return 0; else return reversedNum }; // SOLUTION 2 (BEST RUNTIME - 60MS) var reverse = function(x) { const limit = 2147483648; const reversedNum = parseFloat(x.toString().split("").reverse().join("")) return reversedNum > limit ? 0 : reversedNum * Math.sign(x); }; // SOLUTION 3 (RUNTIME - 60MS) var reverse = function(x) { const sign = x < 0 ? -1 : 1; const positiveX = x * sign; const y = parseInt(positiveX.toString().split('').reverse().join('')) * sign; const absoluteY = y * sign; //0x7FFFFFFF is a number in hexadecimal (2,147,483,647 in decimal) that represents the maximum positive value for a 32-bit signed binary integer return absoluteY <= (y < 0 ? 0x80000000 : 0x7FFFFFFF) ? y : 0; };
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter