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<=231−1

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:
c 复制代码
bool isPowerOfTwo(int n) {
    if (n <= 0) {
        return false;
    }
    return (n & (n - 1)) == 0;
}
相关推荐
Mr YiRan4 小时前
C++面向对象继承与操作符重载
开发语言·c++·算法
蚊子码农8 小时前
算法题解记录--239滑动窗口最大值
数据结构·算法
liliangcsdn8 小时前
A3C算法从目标函数到梯度策略的探索
算法
陈天伟教授9 小时前
人工智能应用- 材料微观:06.GAN 三维重构
人工智能·神经网络·算法·机器学习·重构·推荐算法
liliangcsdn9 小时前
A3C强化学习算法的探索和学习
算法
Figo_Cheung10 小时前
Figo《量子几何学:从希尔伯特空间到全息时空的统一理论体系》(二)
算法·机器学习·几何学·量子计算
额,不知道写啥。10 小时前
HAO的线段树(中(上))
数据结构·c++·算法
LYS_061810 小时前
C++学习(5)(函数 指针 引用)
java·c++·算法
紫陌涵光10 小时前
669. 修剪二叉搜索树
算法·leetcode