/** * @param {number} x * @return {number} */ var reverse = function(x) { let rev = 0; while (x !== 0) { const digit = x % 10; x = ~~(x / 10); rev = rev * 10 + digit; if (rev < Math.pow(-2, 31) || rev > Math.pow(2, 31) - 1) { return 0; } } return rev; };
方法二:转为字符串->数组,然后用数组的reverse
var reverse = function(x) { let d = Array.from((Number(x)+‘‘)); let minus = false; if(d[0] == ‘-‘){ d.shift(); minus = true; } let str = (minus?‘-‘:‘‘)+d.reverse().join(‘‘); let rev = Number(str); if (rev < Math.pow(-2, 31) || rev > Math.pow(2, 31) - 1) { return 0; } return rev; }
原文:https://www.cnblogs.com/yanjianjiang/p/14742058.html