LeetCode //C - 231. Power of Two

231. 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 n == 2^x n==2x.
 

Example 1:

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

Example 2:

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

Example 3:

Input: n = 3
Output: false

Constraints:
  • − 2 31 < = n < = 2 31 − 1 -2^{31} <= n <= 2^{31} - 1 231<=n<=2311

From: LeetCode
Link: 231. Power of Two


Solution:

Ideas:
  1. Check if n is positive: The condition if (n <= 0) ensures that negative numbers and zero return false, since powers of two are always positive.
  2. Bitwise check: The expression (n & (n - 1)) == 0 checks if n has exactly one bit set.
Code:
bool isPowerOfTwo(int n) {
    if (n <= 0) {
        return false;
    }
    return (n & (n - 1)) == 0;
}

相关推荐

  1. LeetCode231. Power of Two

    2024-07-18 13:58:04       51 阅读
  2. UVA-213

    2024-07-18 13:58:04       52 阅读
  3. Leetcode | 231. 2 的幂 C语言

    2024-07-18 13:58:04       50 阅读
  4. 动态规划专练( 231.打家劫舍Ⅱ)

    2024-07-18 13:58:04       28 阅读

最近更新

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

    2024-07-18 13:58:04       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-18 13:58:04       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-18 13:58:04       58 阅读
  4. Python语言-面向对象

    2024-07-18 13:58:04       69 阅读

热门阅读

  1. Leetcode617. 两个二叉树相加

    2024-07-18 13:58:04       17 阅读
  2. request method ‘DELETE‘ is not supported问题

    2024-07-18 13:58:04       22 阅读
  3. 【日常技能】excel 换行符替换的3个方法完美解决

    2024-07-18 13:58:04       21 阅读
  4. C# —— Sort排序

    2024-07-18 13:58:04       24 阅读
  5. centos跳过首次创建用户

    2024-07-18 13:58:04       21 阅读
  6. 使用Spring Retry实现重试机制

    2024-07-18 13:58:04       21 阅读
  7. 一行命令实现 Github 国内下载加速

    2024-07-18 13:58:04       22 阅读
  8. kotlin 退出Activity 平滑动画

    2024-07-18 13:58:04       21 阅读
  9. C语言面试题

    2024-07-18 13:58:04       21 阅读
  10. 1.1 系统架构概述

    2024-07-18 13:58:04       19 阅读