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;
}
相关推荐
思考的笛卡尔9 分钟前
密码学基础:RSA与AES算法的实现与对比
网络·算法·密码学
格林威6 小时前
常规线扫描镜头有哪些类型?能做什么?
人工智能·深度学习·数码相机·算法·计算机视觉·视觉检测·工业镜头
很㗊7 小时前
C与C++---类型转换
c语言·开发语言
say_fall8 小时前
精通C语言(3. 自定义类型:联合体和枚举)
c语言·开发语言
迎風吹頭髮8 小时前
UNIX下C语言编程与实践38-UNIX 信号操作:signal 函数与信号捕获函数的编写
linux·c语言·unix
La Pulga8 小时前
【STM32】I2C通信—软件模拟
c语言·stm32·单片机·嵌入式硬件·mcu
程序员莫小特8 小时前
老题新解|大整数加法
数据结构·c++·算法
过往入尘土9 小时前
服务端与客户端的简单链接
人工智能·python·算法·pycharm·大模型
zycoder.9 小时前
力扣面试经典150题day1第一题(lc88),第二题(lc27)
算法·leetcode·面试
Dream it possible!9 小时前
LeetCode 面试经典 150_哈希表_存在重复元素 II(46_219_C++_简单)
leetcode·面试·散列表