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;
}
相关推荐
了一梨5 分钟前
在Ubuntu中配置适配泰山派的交叉编译环境
linux·c语言·ubuntu
CQ_YM12 分钟前
数据结构之单向链表
c语言·数据结构·链表
gihigo19981 小时前
matlab 基于瑞利衰落信道的误码率分析
算法
foxsen_xia1 小时前
go(基础06)——结构体取代类
开发语言·算法·golang
foxsen_xia1 小时前
go(基础08)——多态
算法·golang
leoufung1 小时前
用三色 DFS 拿下 Course Schedule(LeetCode 207)
算法·leetcode·深度优先
亦是远方2 小时前
南京邮电大学使用计算机求解问题实验一(C语言简单编程练习)
c语言·开发语言·实验报告·南京邮电大学
im_AMBER2 小时前
算法笔记 18 二分查找
数据结构·笔记·学习·算法
C雨后彩虹3 小时前
机器人活动区域
java·数据结构·算法·华为·面试
MarkHD3 小时前
车辆TBOX科普 第53次 三位一体智能车辆监控:电子围栏算法、驾驶行为分析与故障诊断逻辑深度解析
算法