挑战Leetcode刷题30天,[7]整数反转

69 阅读1分钟

给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。

如果反转后整数超过 32 位的有符号整数的范围 [−231, 231 − 1] ,就返回 0。

假设环境不允许存储 64 位整数(有符号或无符号)。

示例 1:

输入:x = 123 输出:321

示例 2:

输入:x = -123 输出:-321

示例 3:

输入:x = 120 输出:21

示例 4:

输入:x = 0 输出:0

提示:

  • -231 <= x <= 231 - 1

Related Topics

  • 数学

解题思路

这个函数就是数组里面的反转函数(reverse),拿到数字后先转成字符串,循环最后一个拼接前一个字符串,这个需要处理下就是负数的情况,需要把“-”提到最前面。

看了下评论都是 乘十 除以10,我觉得还是这种方式好理解

代码

//leetcode submit region begin(Prohibit modification and deletion)
/**
 * @param {number} x
 * @return {number}
 */
var reverse = function (x) {
  let res = '';
  let n = x.toString().length
  for (let i = 0; i < n; i++) {
    res += x.toString()[n - i - 1]
  }
  if (res.indexOf('-') > -1) res = '-' + res.replace('-', '');
  res = Number(res)
  if (res > Math.pow(2, 31) || res < Math.pow(-2, 31)) return 0
  return res;
};
console.log(reverse(123))
console.log(reverse(0))
console.log(reverse(-123))
console.log(reverse(-123))
//leetcode submit region end(Prohibit modification and deletion)

截图