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;
}
相关推荐
北_鱼7 分钟前
支持向量机(SVM):算法讲解与原理推导
算法·机器学习·支持向量机
MZWeiei2 小时前
PTA:运用顺序表实现多项式相加
算法
GISer_Jing2 小时前
Javascript排序算法(冒泡排序、快速排序、选择排序、堆排序、插入排序、希尔排序)详解
javascript·算法·排序算法
cookies_s_s2 小时前
Linux--进程(进程虚拟地址空间、页表、进程控制、实现简易shell)
linux·运维·服务器·数据结构·c++·算法·哈希算法
不想编程小谭3 小时前
力扣LeetCode: 2506 统计相似字符串对的数目
c++·算法·leetcode
水蓝烟雨3 小时前
[HOT 100] 2187. 完成旅途的最少时间
算法·hot 100
01_4 小时前
力扣hot100——LRU缓存(面试高频考题)
leetcode·缓存·面试·lru
菜鸟一枚在这4 小时前
深度解析建造者模式:复杂对象构建的优雅之道
java·开发语言·算法
gyeolhada4 小时前
2025蓝桥杯JAVA编程题练习Day5
java·数据结构·算法·蓝桥杯
阿巴~阿巴~4 小时前
多源 BFS 算法详解:从原理到实现,高效解决多源最短路问题
开发语言·数据结构·c++·算法·宽度优先