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;
}
相关推荐
mmmmath_32 小时前
LeetCode.541.反转字符串II
数据结构·算法·leetcode
Navigator_Z2 小时前
LeetCode //MySQL - 1251. Average Selling Price
c语言·算法·leetcode
醇氧3 小时前
MySQL 8.0 系统表损坏与引擎转换故障排查实战
数据结构·算法
Escalating_xu3 小时前
【C语言数据类型和变量·上】从内置类型到变量模型:一次讲透 sizeof、signed/unsigned 与作用域
c语言
大熊背3 小时前
《Color constancy by characterization of illumination chromaticity》之色度色域最大化算法(二)
算法·白平衡·色度·色温
钓鱼的肝3 小时前
梳理(1-5)
c++·经验分享·笔记·算法·青少年编程
aramae4 小时前
模拟实现strlen()函数 (C语言)
c语言·开发语言·后端
参.商.4 小时前
【Day 53】76. 最小覆盖子串
leetcode·golang
HZZD_HZZD4 小时前
CSDN_批发市场水电漏损归因算法LAM的原理与落地
嵌入式硬件·物联网·算法