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;
}
相关推荐
ChillJavaGuy10 小时前
常见限流算法详解与对比
java·算法·限流算法
sali-tec10 小时前
C# 基于halcon的视觉工作流-章34-环状测量
开发语言·图像处理·算法·计算机视觉·c#
Gu_shiwww11 小时前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
你怎么知道我是队长12 小时前
C语言---循环结构
c语言·开发语言·算法
艾醒12 小时前
大模型面试题剖析:RAG中的文本分割策略
人工智能·算法
程序猿编码12 小时前
基于 Linux 内核模块的字符设备 FIFO 驱动设计与实现解析(C/C++代码实现)
linux·c语言·c++·内核模块·fifo·字符设备
纪元A梦14 小时前
贪心算法应用:K-Means++初始化详解
算法·贪心算法·kmeans
_不会dp不改名_14 小时前
leetcode_21 合并两个有序链表
算法·leetcode·链表
mark-puls14 小时前
C语言打印爱心
c语言·开发语言·算法
Python技术极客14 小时前
将 Python 应用打包成 exe 软件,仅需一行代码搞定!
算法