Skip to content

LeetCode题解:7. 整数反转,迭代,JavaScript,详细注释 #439

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
chencl1986 opened this issue Sep 7, 2023 · 0 comments
Open

Comments

@chencl1986
Copy link
Owner

原题链接:
https://leetcode.cn/problems/reverse-integer

解题思路:

  1. 使用result存储反转后结果,初始值为0
  2. 每次循环取出x的个位数curr,再将x向右移动一位。
  3. result向左移动一位,并将curr存入result的个位数。
  4. 不断循环直到x0,即可完成反转。
  5. x为负数时,正整数部分的反转结果与正数是一样的。因此可以将x都转为正整数处理,完成后再判断是否需要返回负数。
/**
 * @param {number} x
 * @return {number}
 */
var reverse = function (x) {
  let result = 0; // 储存结果
  // 正负数除了符号以外,处理结果是一样的,因此都转换为正数处理
  let pos = x > 0 ? x : Math.abs(x);

  // 不断循环直到pos为0
  while (pos !== 0) {
    // 取出pos的个位数字
    const curr = pos % 10;

    // 将result向左移动一位,将curr存入result的个位,完成一次反转
    result = result * 10 + curr;
    // 将pos向右移动一位,并去除小数
    pos = Math.floor(pos / 10);

    // 如果移动后的结果大于2^31 − 1,则返回0
    if (result > 0x7fffffff) {
      return 0;
    }
  }

  // 判断x的正负,并返回相应结果
  return x > 0 ? result : -result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant