[7] 整数反转

发布时间 2023-11-22 10:29:31作者: 人恒过
/**
 * @param {number} x
 * @return {number}
 */
var reverse = function (x) {
  let result = 0;
  let p = 1;

  if (x < 0) {
    x = -x;
    p = -1;
  }

  while (x > 0) {
    let pop = x % 10;
    x = Math.floor(x / 10);

    if (
      result > Math.pow(2, 31) / 10 ||
      (result == Math.pow(2, 31) / 10 && pop > 7)
    ) {
      return 0;
    }

    if (
      result < -Math.pow(2, 31) / 10 ||
      (result == -Math.pow(2, 31) / 10 && pop < -8)
    ) {
      return 0;
    }

    result = result * 10 + pop;
  }

  return result * p;
};