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;
}
相关推荐
浅念同学4 分钟前
算法.图论-并查集上
java·算法·图论
何不遗憾呢12 分钟前
每日刷题(算法)
算法
立志成为coding大牛的菜鸟.17 分钟前
力扣1143-最长公共子序列(Java详细题解)
java·算法·leetcode
鱼跃鹰飞17 分钟前
Leetcode面试经典150题-130.被围绕的区域
java·算法·leetcode·面试·职场和发展·深度优先
liangbm323 分钟前
数学建模笔记——动态规划
笔记·python·算法·数学建模·动态规划·背包问题·优化问题
潮汐退涨月冷风霜28 分钟前
机器学习之非监督学习(四)K-means 聚类算法
学习·算法·机器学习
B站计算机毕业设计超人34 分钟前
计算机毕业设计Python+Flask微博情感分析 微博舆情预测 微博爬虫 微博大数据 舆情分析系统 大数据毕业设计 NLP文本分类 机器学习 深度学习 AI
爬虫·python·深度学习·算法·机器学习·自然语言处理·数据可视化
羊小猪~~38 分钟前
深度学习基础案例5--VGG16人脸识别(体验学习的痛苦与乐趣)
人工智能·python·深度学习·学习·算法·机器学习·cnn
重生之我在20年代敲代码2 小时前
strncpy函数的使用和模拟实现
c语言·开发语言·c++·经验分享·笔记
limingade4 小时前
手机实时提取SIM卡打电话的信令和声音-新的篇章(一、可行的方案探讨)
物联网·算法·智能手机·数据分析·信息与通信