最简单的方式是直接将数字转为字符串, 然后split
成数组, 反转后, 过滤掉-
符号, 再转为数字.
/**
* @param {number} x
* @return {number}
*/
var reverse = function(x) {
const MAX = Math.pow(2, 31)
const inRange = num => (num < MAX) && (num > 1 - MAX)
if (!inRange(x)) return 0
const arr = (x + '').split('')
const isNegative = x < 0
const noSymbol = str => str !== '-'
const str = arr.filter(noSymbol).reverse().join('')
const num = isNegative ? (0 - Number(str)) : (0 + Number(str))
return inRange(num) ? num : 0
};
以上方法涉及到类型转换, 不转换的时候可以直接对数字进行运算, 通过不断将原数据除10, 相加到另一数字上, 来获得最终的数据.
/**
* @param {number} x
* @return {number}
*/
var reverse = function(x) {
const MAX = 2147483647
const MIN = -2147483648
const inRange = num => (num < MAX) && (num > MIN)
if (!inRange(x)) return 0
let result = 0
const isNegative = x < 0
let source = Math.abs(x)
let length = 0
while (++length <= 10) {
const tmp = source % 10
source = (source / 10) >>> 0
result = (tmp < 1 && source < 1) ? result : (result * 10 + tmp)
console.log(length, tmp, source, result)
}
const num = isNegative ? (0 - result) : (0 + result)
return inRange(num) ? num : 0
};
reverse(1534236469)