LeetCode //C - 342. Power of Four

342. Power of Four

Given an integer n, return true if it is a power of four. Otherwise, return false.

An integer n is a power of four, if there exists an integer x such that n = = 4 x n == 4^x n==4x.

Example 1:

Input: n = 16
Output: true

Example 2:

Input: n = 5
Output: false

Example 3:

Input: n = 1
Output: true

Constraints:
  • − 2 31 < = n < = 2 31 − 1 -2^{31} <= n <= 2^{31} - 1 −231<=n<=231−1

From: LeetCode

Link: 342. Power of Four


Solution:

Ideas:
  • n > 0: Ensures the number is positive.
  • (n & (n - 1)) == 0: This checks if n is a power of two.
  • (n & 0x55555555) != 0: This checks that the single bit set in n is in an odd position, confirming that n is a power of four.
Code:
c 复制代码
bool isPowerOfFour(int n) {
    // Check if n is positive and a power of two
    if (n > 0 && (n & (n - 1)) == 0) {
        // Check if the single set bit is in an odd position
        return (n & 0x55555555) != 0;
    }
    return false;
}
相关推荐
报错小能手31 分钟前
刷题日常 5 二叉树最大深度
算法
Greedy Alg1 小时前
LeetCode 84. 柱状图中最大的矩形(困难)
算法
im_AMBER1 小时前
Leetcode 52
笔记·学习·算法·leetcode
小欣加油1 小时前
leetcode 946 验证栈序列
c++·算法·leetcode·职场和发展
dqsh061 小时前
树莓派5+Ubuntu24.04 LTS CH348 / CH9344 驱动安装 保姆级教程
linux·c语言·单片机·嵌入式硬件·iot
包饭厅咸鱼2 小时前
PaddleOCR----制作数据集,模型训练,验证 QT部署(未完成)
算法
无敌最俊朗@2 小时前
C++ 并发与同步速查笔记(整理版)
开发语言·c++·算法
王哈哈^_^2 小时前
【完整源码+数据集】课堂行为数据集,yolo课堂行为检测数据集 2090 张,学生课堂行为识别数据集,目标检测课堂行为识别系统实战教程
人工智能·算法·yolo·目标检测·计算机视觉·视觉检测·毕业设计
夏鹏今天学习了吗2 小时前
【LeetCode热题100(66/100)】寻找两个正序数组的中位数
算法·leetcode·职场和发展