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;
}
相关推荐
Han.miracle1 天前
数据结构——二叉树的从前序与中序遍历序列构造二叉树
java·数据结构·学习·算法·leetcode
mit6.8241 天前
前后缀分解
算法
你好,我叫C小白1 天前
C语言 循环结构(1)
c语言·开发语言·算法·while·do...while
朱嘉鼎1 天前
状态机的介绍
c语言·单片机
寂静山林1 天前
UVa 10228 A Star not a Tree?
算法
Neverfadeaway1 天前
【C语言】深入理解函数指针数组应用(4)
c语言·开发语言·算法·回调函数·转移表·c语言实现计算器
一碗绿豆汤1 天前
c语言-流程控制语句
c语言
子牙老师1 天前
从零手写gdb调试器
c语言·linux内核·gdb·调试器
Madison-No71 天前
【C++】探秘vector的底层实现
java·c++·算法
Swift社区1 天前
LeetCode 401 - 二进制手表
算法·leetcode·ssh