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;
}
相关推荐
什巳35 分钟前
JAVA练习306- 翻转二叉树
java·数据结构·算法·leetcode
一个初入编程的小白39 分钟前
C语言:函数栈帧与销毁
c语言·开发语言
smj2302_7968265242 分钟前
解决leetcode第3989题网格中保持一致的最大列数
python·算法·leetcode
巧克力男孩dd2 小时前
Python超典型练习题(第一次作业)
开发语言·python·算法
爱刷碗的苏泓舒2 小时前
平方根信息滤波:矩阵推导及 GNSS 参数估计应用
线性代数·算法·矩阵·gnss·参数估计·测量平差·平方根信息滤波
想做小南娘,发现自己是女生喵3 小时前
第 2 章 顺序表和 vector
java·数据结构·算法
ComputerInBook3 小时前
c 和 c++ 中的宏块(macro)
c语言·c++··宏块·宏指令
艾醒4 小时前
2026年第29周(7.13-7.19)AI全复盘:技术突破、行业趣闻翻车、算力服务器商业动态
人工智能·算法
雪碧聊技术4 小时前
动态规划算法—01背包问题
算法·动态规划
bu_shuo4 小时前
c与cpp中的argc和argv
c语言·c++·算法