Skip to content

LeetCode题解:231. 2的幂,递归,JavaScript,详细注释 #214

Description

@chencl1986

原题链接:https://leetcode-cn.com/problems/power-of-two/

解题思路:

  1. 如果一个数是2的幂次方,表示如果将其不断除以2,最终结果为1。
  2. 如果一个数不是2的幂次方,那么将其不断除以2,其中间结果会出现一个不为1的奇数。
  3. 因此可以用递归,将其不断除以2,在中间结果为奇数时,判断其结果是否为1,为1表示n是2的幂次方。
  4. 如果当前结果为偶数,则将当前值除以2,继续递归。
  5. 当n为0时,会造成死循环,因此需要特别判断。
/**
 * @param {number} n
 * @return {boolean}
 */
var isPowerOfTwo = function (n) {
  // 当n=0时,Math.floor(n % 2)将始终为0,造成死循环,因此需要特殊处理
  // 当n<0时,n必然不是2的幂次方
  if (n === 0) {
    return false;
  }

  // 如果一个数为2的幂次方,代表它可以被2整除,并且它一定是偶数
  // 因此如果它不断除以2,如果它是2的幂次方,则最终n会等于1
  // 如果它不是2的幂次方,表示它不是2的幂次方
  if (n % 2) {
    // 根据n最终是否等于1,判断它是否2的幂次方
    return n === 1 ? true : false;
  } else {
    // 将当前值除以2后继续递归
    return isPowerOfTwo(n / 2);
  }
};

No activity

Activity on this issue will appear here.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions