题目Given a 32-bit signed integer, reverse digits of an integer.反转整数反转后的整数如果不在[−2^31, 2^31 − 1]范围则返回0Example1Input: 123Output: 321Example2Input: -123Output: -321Example3Input: 120Output: 21简单解法耗时:100msvar reverse = function(x) { const max = Math.pow(2,31) -1 const min = -1 * Math.pow(2,31) let arr = String(x).split(’’).reverse(); const len = arr.length - 1; if(arr[0] === 0){ arr = arr.splice(0,1) } if(arr[len] === ‘-’){ arr.splice(len,1) arr.unshift(’-’) } const reverseX = Number(arr.join(’’)) if(reverseX > max || reverseX < min) return 0 return reverseX};解法二:var reverse = function(x) { const MAX = Math.pow(2,31) - 1 const MIN = -1 * Math.pow(2,31) let res = 0; while (x !== 0) { // 获取余数,即从右边第一位开始的数字 res = res * 10 + (x % 10); //保留整数部分 x = Math.trunc(x / 10); } return (res > MAX || res < MIN) ? 0 : res;};解题思路:2341: res = 4,x = 232: res = 410 + (23%10) = 40 + 3 = 43, x: Math.trunc(23/10) = 23: res = 4310 + (2%10) = 430 + 2 = 432 x = Math.trunc(2/10) = 0跳出while循环,判断res是否在最大值和最小值之间知识点复习Math.floor(x) //小于x的最大整数Math.floor(-123/10) // -13Math.floor(x) // 返回四舍五入Math.round(-126/10) // -13Math.trunc(x) // 返回x的整数部分,包含正负号Math.trunc(-123/10) // -12