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;
}
相关推荐
罗西的思考1 小时前
【轻量化复刻大模型 / KIMI K3】Multi-Token Prediction(MTP / EAGLE-3)(2)
人工智能·算法·机器学习
罗西的思考1 小时前
【轻量化复刻大模型 / KIMI K3】Multi-Token Prediction(MTP / EAGLE-3)(1)
人工智能·算法·机器学习
武子康3 小时前
H3-World 接入 Game Agent:谁来判断门真的打开了?
人工智能·算法·机器学习
文丑颜不良啊6 小时前
LeetCode3001~3020题目解析
java·leetcode
Zwawa7 小时前
陀螺仪数据为什么看起来总在动:零偏、噪声和零漂
c语言·单片机·嵌入式
武子康8 小时前
H3-World 扩展跳跃与开门:新动作怎样进入训练数据?
大数据·人工智能·算法
卡尔曼的BD SLAMer8 小时前
北斗导航 |GNSS ION论文集汇总1997到2022(链接在文末)
算法·北斗导航
时间的拾荒人8 小时前
Redis Cluster 集群详解:分片算法、搭建、故障处理与扩容实战
数据库·redis·算法·集群
soso19689 小时前
低功耗设计与BMS开发指南
c语言·开发语言·汇编
老师我太想进步了202610 小时前
【数据结构-8】栈的实现
c语言·数据结构·算法