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;
}
相关推荐
_F_y1 小时前
MySQL用C/C++连接
c语言·c++·mysql
BackCatK Chen1 小时前
C语言学习栏目目录
c语言·保姆级教程·c语言入门·c语言学习栏目目录
极客数模3 小时前
【2026美赛赛题初步翻译F题】2026_ICM_Problem_F
大数据·c语言·python·数学建模·matlab
A_nanda4 小时前
c# MOdbus rto读写串口,如何不相互影响
算法·c#·多线程
代码雕刻家5 小时前
2.4.蓝桥杯-分巧克力
算法·蓝桥杯
Ulyanov6 小时前
顶层设计——单脉冲雷达仿真器的灵魂蓝图
python·算法·pyside·仿真系统·单脉冲
请注意这个女生叫小美6 小时前
C语言 斐波那契而数列
c语言
Legendary_0087 小时前
Type-C 一拖二快充线:突破单口限制的技术逻辑
c语言·开发语言
智者知已应修善业7 小时前
【查找字符最大下标以*符号分割以**结束】2024-12-24
c语言·c++·经验分享·笔记·算法
91刘仁德7 小时前
c++类和对象(下)
c语言·jvm·c++·经验分享·笔记·算法