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;
}
相关推荐
setmoon2141 分钟前
C++中的观察者模式实战
开发语言·c++·算法
2403_835568473 分钟前
C++代码规范化工具
开发语言·c++·算法
tankeven18 分钟前
HJ138 在树上游玩
c++·算法
lihihi1 小时前
P1209 [USACO1.3] 修理牛棚 Barn Repair
算法
weixin_387534221 小时前
Ownership - Rust Hardcore Head to Toe
开发语言·后端·算法·rust
xsyaaaan1 小时前
leetcode-hot100-链表
leetcode·链表
庞轩px1 小时前
MinorGC的完整流程与复制算法深度解析
java·jvm·算法·性能优化
Queenie_Charlie1 小时前
Manacher算法
c++·算法·manacher
闻缺陷则喜何志丹1 小时前
【树的直径 离散化】 P7807 魔力滋生|普及+
c++·算法·洛谷·离散化·树的直径
AI_Ming2 小时前
Seq2Seq-大模型知识点(程序员转行AI大模型学习)
算法·ai编程