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;
}
相关推荐
CPUOS20103 小时前
嵌入式C语言高级编程之MVC设计模式
c语言·设计模式·mvc
jolimark3 小时前
C语言存在的问题及Zig语言如何改进,差异对比全在这
c语言·内存管理·系统编程·类型系统·zig语言
leobertlan3 小时前
好玩系列:用20元实现快乐保存器
android·人工智能·算法
青梅橘子皮3 小时前
C语言---指针的应用以及一些面试题
c语言·开发语言·算法
_深海凉_4 小时前
LeetCode热题100-有效的括号
linux·算法·leetcode
零号全栈寒江独钓7 小时前
基于c/c++实现linux/windows跨平台获取ntp网络时间戳
linux·c语言·c++·windows
被开发耽误的大厨7 小时前
1、==、equals、hashCode底层原理?重写场景?
算法·哈希算法
WolfGang0073217 小时前
代码随想录算法训练营 Day38 | 动态规划 part11
算法·动态规划
松☆8 小时前
C++ 算法竞赛题解:P13569 [CCPC 2024 重庆站] osu!mania —— 浮点数精度陷阱与 `eps` 的深度解析
开发语言·c++·算法
爱编码的小八嘎9 小时前
C语言完美演绎8-10
c语言