当前位置:网站首页>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);
}
};
位运算常用技巧

边栏推荐
- 【嵌入式C基础】第7篇:C语言流程控制详讲
- Black Scholes Merton European option pricing formula
- STM32 Development Notes - experience sharing
- [embedded C foundation] Part 4: use of operators
- RGB game atmosphere light touch chip-dlt8s04a-jericho
- Tidb 6.x in action was released, a summary of 6.x practices that condense the collective wisdom of the community!
- Summary: idea problem record
- 面试必问,敲重点!讲一下 Android Application 启动流程及其源码?
- [embedded C foundation] Part 7: detailed introduction to C language process control
- Analysis of Andriod low on memory printing principle
猜你喜欢

为什么说Crypto游戏正在改变游戏产业?

Fundamentals of machine learning Bayesian analysis-14

Redefinition problem of defining int i variable in C for loop

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

2020-12-07

Installation and reinstallation of win11 system graphic version tutorial

Chapter 6 提升
![[pictures and texts] detailed tutorial of one click reinstallation of win11 system](/img/cc/749fe4095fc5afb1fc2c65df43d06c.png)
[pictures and texts] detailed tutorial of one click reinstallation of win11 system

SSH port forwarding (Tunneling Technology)
随机推荐
Databinding+LiveData轻松实现无重启换肤
03 pyechars rectangular coordinate system chart (example code + effect drawing)
butterfly spreads
[graduation design] heart rate detection system based on single chip microcomputer - STM32 embedded Internet of things
MySQL 实践篇 —— 主从复制
.net for subtraction, intersection and union of complex type sets
【嵌入式C基础】第9篇:C语言指针的基本用法
Remove the plug-in of category in WordPress link
Bear market spread portfolio
Fast classification of array.group() in ES6
[graduation design] oscilloscope design and Implementation Based on STM32 - single chip microcomputer Internet of things
Change the document type in endnode and import it in word
What if the win11 folder cannot be opened
Smart touch screen LCD bathroom mirror light touch chip-dlt8t02s-jericho
Mysql中DQL基本练习
Black cat takes you to learn EMMC protocol chapter 27: what is EMMC's dynamic capacity?
Phpstudy steps to quickly build a website (teach you to build it by hand)
面试必问,敲重点!讲一下 Android Application 启动流程及其源码?
Leetcode daily question (2196. create binary tree from descriptions)
【嵌入式C基础】第3篇:常量和变量