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;
}
相关推荐
im_AMBER7 小时前
算法笔记 05
笔记·算法·哈希算法
夏鹏今天学习了吗7 小时前
【LeetCode热题100(46/100)】从前序与中序遍历序列构造二叉树
算法·leetcode·职场和发展
吃着火锅x唱着歌7 小时前
LeetCode 2389.和有限的最长子序列
算法·leetcode·职场和发展
嶔某7 小时前
二叉树的前中后序遍历(迭代)
算法
WWZZ20257 小时前
快速上手大模型:机器学习2(一元线性回归、代价函数、梯度下降法)
人工智能·算法·机器学习·计算机视觉·机器人·大模型·slam
孤狼灬笑7 小时前
深度学习经典分类(算法分析与案例)
rnn·深度学习·算法·cnn·生成模型·fnn
dragoooon347 小时前
[优选算法专题四.前缀和——NO.26二维前缀和]
算法
苏小瀚9 小时前
算法---位运算
java·算法
Code小翊9 小时前
归并排序基础理解
数据结构·算法·排序算法
.小小陈.9 小时前
数据结构2:单链表
c语言·开发语言·数据结构·笔记·学习方法