当前位置:网站首页>leetcdoe-342. 4的幂
leetcdoe-342. 4的幂
2022-07-28 12:08:00 【KGundam】
位运算
题目详情
给定一个整数,写一个函数来判断它是否是 4 的幂次方。如果是,返回 true ;否则,返回 false 。
整数 n 是 4 的幂次方需满足:存在整数 x 使得 n == 4^x
示例1:
输入:n = 16
输出:true
示例2:
输入:n = 5
输出:false
示例3:
输入:n = 1
输出:true
思路:
当一个数字n是2的整数次方时:那么它的二进制一定是0...010...0这样的形式(只有一位是1)
n-1的二进制就是0...001...1 则可以得到: n & (n-1) == 0 ==> 这个数是2的整数次方
那么如果n也是4的整数次方呢?那么二进制中的1的位置一定得是奇数位(且只有这一个),例如0...010...1000...10000 题目中n的范围是-2^31 <= n <= 2^31 - 1 即二进制的32位
所以我们可以利用10101...101(32位奇数位全为1偶数位全为0) 让n和它做与运算
结果如果不为0说明n的二进制中奇数位有一个1,即n是4的整数次方
我的代码:
class Solution
{
public:
bool isPowerOfFour(int n)
{
// n为2的整数次方 10101...101的十六进制表示
return n > 0 && !(n & (n - 1)) && (n & 0x55555555);
}
};
位运算常用技巧

边栏推荐
- Intrinsic value and time value of options
- 【嵌入式C基础】第3篇:常量和变量
- QT signal and slot mechanism (detailed)
- What if the win11 folder cannot be opened
- Code layered management of interface testing based on RF framework
- 【嵌入式C基础】第7篇:C语言流程控制详讲
- Jetpack 全家桶之 LiveData 使用及源码篇
- Low code: reduce technical capability requirements and improve software development efficiency
- Le transaction
- Pointnet++ Chinese Translation
猜你喜欢

Jetpack Compose 完全脱离 View 系统了吗?

【C语言易错点】第4篇:结构体在内存中存储规则详讲
![[FPGA] FIR filter - half band filter](/img/6e/d97b3842f80e37aa41b888384a14cb.png)
[FPGA] FIR filter - half band filter

Intrinsic value and time value of options

Chinese translation of pointnet:deep learning on point sets for 3D classification and segmentation

Fast classification of array.group() in ES6

Installation and reinstallation of win11 system graphic version tutorial

How to open the power saving mode of win11 system computer

What if the right button of win11 start menu doesn't respond

机器学习基础-决策树-12
随机推荐
Definition of option basis
LeetCode·每日一题·1331.数组序号转换·离散化
Summary: idea problem record
Storage model: big end and small end
Android工程师,如何使用Kotlin提供生产力?
Machine learning Basics - decision tree-12
[embedded C foundation] Part 7: detailed introduction to C language process control
Xampp Chinese tutorial guide
Sub thread update UI full solution
拥有游戏的一部分,写在我的世界禁用NFT之后
Black cat takes you to learn UFS agreement part 2: Interpretation of UFS related terms
[July 5 event preview] Flink Summit
A brief introduction to the for loop. Some of the code involves arrays
BiliBili Yang Zhou: above efficiency, efficient delivery
How to open the power saving mode of win11 system computer
[matlab] IIR filter
【嵌入式C基础】第8篇:C语言数组讲解
03 pyechars rectangular coordinate system chart (example code + effect drawing)
How to add PDF virtual printer in win11
Full disclosure! Huawei cloud distributed cloud native technology and Practice