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;
}
相关推荐
程序员小明儿1 天前
量子计算探秘:从零开始的量子编程与算法之旅 · 第五篇
算法·量子计算
灰色小旋风1 天前
力扣第九题C++回文数
c++·算法·leetcode
串口哑火达人1 天前
(七)RT-Thread物联网实战--MQTT-cJSON-OneNET
c语言·单片机·嵌入式硬件·mcu·物联网
爱编码的小八嘎1 天前
C语言完美演绎3-9
c语言
vx-bot5556661 天前
企业微信ipad协议的增量同步算法与差量更新机制
算法·企业微信·ipad
cpp_25011 天前
P1359 租用游艇
c++·算法·题解·洛谷·线性dp
Naisu Xu1 天前
数学笔记:最小二乘法(直线拟合)
笔记·算法·最小二乘法
weixin_395448911 天前
main.c_raw_0311_lyp
前端·网络·算法
weixin_649555671 天前
C语言程序设计第四版(何钦铭、颜晖)第七章之利用数组求矩阵各行元素之和并输出
c语言·算法·矩阵
智者知已应修善业1 天前
【输入矩阵将其按副对角线交换后输出】2024-11-27
c语言·c++·经验分享·笔记·线性代数·算法·矩阵