LeetCode刷题之反转数字

219 阅读1分钟

leetcode刷题第二题整数反转

  • 该题目就是讲数字的顺序进行反转,比较重要的步骤为弹出和推入,操作如下
  • 取模
  • 取余
    • 弹出和推入数字
    • [弹出]为: num = origin % 10;num /= 10;
    • [推入]为:result = result * 10 + num;
  • 模式识别
    • INT_MAX和INT_MIN,js的话对应的就是Math.pow(2,31)-1和Math.pow(-2,31)
    • 此举是防止数字溢出
  • 案例推演
    • 假设有一个数字1234,反转后应为4321
    • 首先我们可以对取最后一位4,res = res * 10 + x % 10 = 4,然后取整去除数字4 => 123
    • 取第二位3,,res = res * 10 + x % 10 = 43,然后取整去除数字3 => 12
    • 取第三位2,,res = res * 10 + x % 10 = 432,然后取整去除数字2 => 1
    • 最后,res = res * 10 + x % 10 = 4321,然后取整去除数字1,此时x = 0,循环结束,得到结果4321
  • 算法
  var reverse = function (x) {
      let res = 0
      if (typeof x === 'number') return 0
      while(x) {
        res = res * 10 + x % 10
        if (x > Math.pow(2, 31) - 1 || x < Math.pow(-2, 31)) {
          return 0
        }
        x = ~~(x / 10)
      }
      return res
  }