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;
}
相关推荐
头歌实践平台17 小时前
LL(1)文法分析
算法
计算机安禾17 小时前
【算法分析与设计】第6篇:动态规划的原理:最优子结构与重叠子问题
算法
Larcher17 小时前
数组去重算法:理论与实践深度解析
javascript·算法·代码规范
CS创新实验室17 小时前
数据结构和算法:摊还分析
java·数据结构·算法
curry____30317 小时前
邻接矩阵 和 领接表 和 链式前向星对比
数据结构·c++·算法
通信小呆呆17 小时前
维度分数傅里叶时频图 + 图神经网络:突破传统时频分析的目标识别与杂波抑制新框架
人工智能·神经网络·算法
csdn_aspnet17 小时前
C++ 算法 LeetCode 编号 70 - 爬楼梯
开发语言·c++·算法·leetcode
he___H17 小时前
leetcode100-合并区间
java·数据结构·算法
神仙别闹17 小时前
基于C语言来实现图形界面画板的功能
c语言·开发语言·单片机
圣保罗的大教堂18 小时前
leetcode 2770. 达到末尾下标所需的最大跳跃次数 中等
leetcode