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;
}
相关推荐
当归10241 分钟前
接雨水的算法
android·java·算法
MSTcheng.38 分钟前
【C语言】指针(5)
c语言·开发语言
╮壞孩子的天39 分钟前
C语言多人聊天室 ---chat(客户端聊天)
c语言·开发语言
IT猿手1 小时前
2025高维多目标优化:基于导航变量的多目标粒子群优化算法(NMOPSO)的无人机三维路径规划,MATLAB代码
开发语言·人工智能·算法·机器学习·matlab·无人机·cocos2d
阿乾之铭1 小时前
动态规划算法
算法·动态规划
菠菠萝宝1 小时前
【代码随想录】第九章-动态规划(上)
算法·动态规划·01背包·完全背包·多重背包·上楼梯
DTDanteDong1 小时前
从头再来!社招找工作——算法题复习九:动态规划
算法·动态规划
Coco_92641 小时前
Hot100 动态规划
算法·动态规划
卑微的小鬼1 小时前
golang的var ,make ,new, := 的区别
算法
01_2 小时前
力扣hot100 ——和为k的子数组 前后缀和(积)各种情况总结
数据结构·算法·leetcode·前后缀和(积)计算