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;
}
相关推荐
yaoh.wang7 分钟前
力扣(LeetCode) 83: 删除排序链表中的重复元素 - 解法思路
程序人生·算法·leetcode·链表·面试·职场和发展
阿昭L12 分钟前
leetcode旋转链表
算法·leetcode·链表
山楂树の13 分钟前
有效的括号(栈)
数据结构·算法
im_AMBER13 分钟前
Leetcode 81 【滑动窗口(定长)】
数据结构·笔记·学习·算法·leetcode
xu_yule18 分钟前
算法基础(背包问题)-完全背包
c++·算法·动态规划·完全背包
x9766620 分钟前
使用 HMAC-SHA256算法对MCU UID进行加密
单片机·嵌入式硬件·算法
gfdhy21 分钟前
【c++】素数详解:概念、定义及高效实现(判断方法 + 筛法)
开发语言·c++·算法·数学建模·ai编程
Swift社区26 分钟前
LeetCode 452 - 用最少数量的箭引爆气球
算法·leetcode·职场和发展
小尧嵌入式30 分钟前
Linux进程线程与进程间通信
linux·运维·服务器·c语言·开发语言·数据结构·microsoft
mjhcsp39 分钟前
题解:P8727 [蓝桥杯 2020 国 A] 填空问题
算法