Skip to content

Instantly share code, notes, and snippets.

@samandar-boymurodov
Created June 6, 2021 07:30
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 samandar-boymurodov/bff99dda575314288b712183f3f66f26 to your computer and use it in GitHub Desktop.
Save samandar-boymurodov/bff99dda575314288b712183f3f66f26 to your computer and use it in GitHub Desktop.
/**
* @param {number} x
* @return {number}
*/
var reverse = function(x) {
let result = 0
let number = Math.abs(x)
for (let i of [...new Array(number.toString().length)].map((e, index) => Number("1" + "0".repeat(index))).reverse()) {
result += (number % 10) * i
number = Math.floor(number / 10)
}
result = x<0 ? -result : result
if (result <= 2**31 -1 && result>= Math.pow(-2, 31)) {
return result
} else {
return 0
}
};
@samandar-boymurodov
Copy link
Author

const reverse = x => {
    const limit = 2147483648;
    const k = x < 0 ? -1 : 1;
    const n = Number(String(Math.abs(x)).split('').reverse().join(''));
    return n > limit ? 0 : n * k;
};

this solution seems very straightforward

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