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;
}
相关推荐
前端炒粉18 小时前
35.LRU 缓存
开发语言·javascript·数据结构·算法·缓存·js
断剑zou天涯20 小时前
【算法笔记】窗口内最大值或最小值的更新结构
java·笔记·算法
smj2302_7968265220 小时前
解决leetcode第3753题范围内总波动值II
python·算法·leetcode
骑着猪去兜风.1 天前
线段树(二)
数据结构·算法
fengfuyao9851 天前
竞争性自适应重加权算法(CARS)的MATLAB实现
算法
薛慕昭1 天前
嵌入式 C 语言猜大小游戏设计与实现
c语言·游戏
散峰而望1 天前
C++数组(二)(算法竞赛)
开发语言·c++·算法·github
leoufung1 天前
LeetCode 92 反转链表 II 全流程详解
算法·leetcode·链表
wyhwust1 天前
交换排序法&冒泡排序法& 选择排序法&插入排序的算法步骤
数据结构·算法·排序算法
利刃大大1 天前
【动态规划:背包问题】完全平方数
c++·算法·动态规划·背包问题·完全背包