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;
}
相关推荐
HABuo4 小时前
【linux文件系统】磁盘结构&文件系统详谈
linux·运维·服务器·c语言·c++·ubuntu·centos
颜酱5 小时前
图结构完全解析:从基础概念到遍历实现
javascript·后端·算法
m0_736919105 小时前
C++代码风格检查工具
开发语言·c++·算法
yugi9878385 小时前
基于MATLAB强化学习的单智能体与多智能体路径规划算法
算法·matlab
DuHz5 小时前
超宽带脉冲无线电(Ultra Wideband Impulse Radio, UWB)简介
论文阅读·算法·汽车·信息与通信·信号处理
Polaris北极星少女6 小时前
TRSV优化2
算法
代码游侠7 小时前
C语言核心概念复习——网络协议与TCP/IP
linux·运维·服务器·网络·算法
2301_763472467 小时前
C++20概念(Concepts)入门指南
开发语言·c++·算法
abluckyboy7 小时前
Java 实现求 n 的 n^n 次方的最后一位数字
java·python·算法
园小异8 小时前
2026年技术面试完全指南:从算法到系统设计的实战突破
算法·面试·职场和发展