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;
}
相关推荐
北上ing14 分钟前
算法练习:19.JZ29 顺时针打印矩阵
算法·leetcode·矩阵
.格子衫.1 小时前
真题卷001——算法备赛
算法
XiaoyaoCarter2 小时前
每日一道leetcode
c++·算法·leetcode·职场和发展·二分查找·深度优先·前缀树
Hygge-star2 小时前
【数据结构】二分查找5.12
java·数据结构·程序人生·算法·学习方法
June`3 小时前
专题二:二叉树的深度搜索(二叉树剪枝)
c++·算法·深度优先·剪枝
小狗祈祷诗4 小时前
day22-数据结构之 栈&&队列
c语言·数据结构
AI+程序员在路上4 小时前
XML介绍及常用c及c++库
xml·c语言·c++
好吃的肘子4 小时前
Elasticsearch架构原理
开发语言·算法·elasticsearch·架构·jenkins
胡耀超5 小时前
霍夫圆变换全面解析(OpenCV)
人工智能·python·opencv·算法·计算机视觉·数据挖掘·数据安全
软行5 小时前
LeetCode 每日一题 3341. 到达最后一个房间的最少时间 I + II
数据结构·c++·算法·leetcode·职场和发展