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 小时前
VS中将cuda项目编译为DLL并调用
算法
课堂剪切板4 小时前
ch03 部分题目思路
算法
山登绝顶我为峰 3(^v^)35 小时前
如何录制带备注的演示文稿(LaTex Beamer + Pympress)
c++·线性代数·算法·计算机·密码学·音视频·latex
Two_brushes.6 小时前
【算法】宽度优先遍历BFS
算法·leetcode·哈希算法·宽度优先
森焱森8 小时前
水下航行器外形分类详解
c语言·单片机·算法·架构·无人机
QuantumStack10 小时前
【C++ 真题】P1104 生日
开发语言·c++·算法
写个博客10 小时前
暑假算法日记第一天
算法
绿皮的猪猪侠10 小时前
算法笔记上机训练实战指南刷题
笔记·算法·pta·上机·浙大
hie9889411 小时前
MATLAB锂离子电池伪二维(P2D)模型实现
人工智能·算法·matlab
杰克尼11 小时前
BM5 合并k个已排序的链表
数据结构·算法·链表