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;
}
相关推荐
ACP广源盛1392462567314 分钟前
(ACP广源盛)GSV6172---MIPI/LVDS 信号转换为 Type-C/DisplayPort 1.4/HDMI 2.0 并集成嵌入式 MCU
c语言·开发语言·单片机·嵌入式硬件·音视频
im_AMBER1 小时前
算法笔记 09
c语言·数据结构·c++·笔记·学习·算法·排序算法
凯芸呢1 小时前
Java中的数组(续)
java·开发语言·数据结构·算法·青少年编程·排序算法·idea
寂静山林2 小时前
UVa 1030 Image Is Everything
算法
AI柠檬2 小时前
几种排序算法的实现和性能比较
数据结构·算法·c#·排序算法
weixin_429630262 小时前
第6章 支持向量机
算法·机器学习·支持向量机
SweetCode2 小时前
C++ 实现大数加法
开发语言·c++·算法
王哈哈^_^2 小时前
【数据集】【YOLO】【目标检测】共享单车数据集,共享单车识别数据集 3596 张,YOLO自行车识别算法实战训推教程。
人工智能·算法·yolo·目标检测·计算机视觉·视觉检测·毕业设计
CodeWizard~3 小时前
AtCoder Beginner Contest 430赛后补题
c++·算法·图论
大大dxy大大3 小时前
机器学习-KNN算法示例
人工智能·算法·机器学习