【LeetCode 0231】【位运算】2的N次方

  1. Power of Two

Given an integer n, return true if it is a power of two. Otherwise, return false.

An integer n is a power of two, if there exists an integer x such that n == 2^x.

Example 1:

**Input:** n = 1
**Output:** true
**Explanation: **2^0 = 1

Example 2:

**Input:** n = 16
**Output:** true
**Explanation: **2^4 = 16

Example 3:

**Input:** n = 3
**Output:** false

Constraints:

  • -2^31 <= n <= 2^31 - 1

Follow up: Could you solve it without loops/recursion?

Idea
首先 2^n 不可能是0或者负数
其次 2^n 作为正数,其二进制位有且只有一个位是1
JavaScript Solution
/**
 * @param {number} n
 * @return {boolean}
 */
var isPowerOfTwo = function(n) {
    return !(n<=0) && !(n&(n-1))
};

相关推荐

  1. LeetCode 0231】【运算2N

    2024-07-21 04:46:02       17 阅读
  2. [C/C++入门][循环]14、计算2幂(2n

    2024-07-21 04:46:02       17 阅读
  3. LeetCode 0050】【分治/递归】求xn

    2024-07-21 04:46:02       20 阅读
  4. henauOJ 1113: 计算xn

    2024-07-21 04:46:02       42 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-21 04:46:02       52 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-21 04:46:02       54 阅读
  3. 在Django里面运行非项目文件

    2024-07-21 04:46:02       45 阅读
  4. Python语言-面向对象

    2024-07-21 04:46:02       55 阅读

热门阅读

  1. 【Socket 编程】基于UDP协议建立多人聊天室

    2024-07-21 04:46:02       16 阅读
  2. 会Excel就会sql?

    2024-07-21 04:46:02       18 阅读
  3. Android笔试面试题AI答之布局Layout(1)

    2024-07-21 04:46:02       12 阅读
  4. SpringBootWeb 篇-入门了解 Swagger 的具体使用

    2024-07-21 04:46:02       22 阅读