当前位置:网站首页>二进制表示--2的幂
二进制表示--2的幂
2022-07-26 00:09:00 【獜洛橙】
问题描述:
给你一个整数 n,请你判断该整数是否是 2 的幂次方。如果是,返回 true ;否则,返回 false 。
如果存在一个整数 x 使得 n == 2x ,则认为 n 是 2 的幂次方。
示例 1:
输入:n = 1
输出:true
解释:20 = 1
示例 2:输入:n = 16
输出:true
解释:24 = 16
示例 3:输入:n = 3
输出:false
示例 4:输入:n = 4
输出:true
示例 5:输入:n = 5
输出:false来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/power-of-two
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
问题分析:
2的幂是比较特殊的,转为二进制只有一位为1,那么与减一的本身去相与,结果肯定是为0,所以判断的条件就是n&(n-1)==0

代码如下:
class Solution {
public:
bool isPowerOfTwo(int n) {
return n>0 && (n&(n-1)) == 0;
}
};边栏推荐
猜你喜欢

Leetcode200 - find detailed explanation of the number of islands

对“DOF: A Demand-oriented Framework for ImageDenoising“的理解

06_ue4进阶_使用地形工具设置大地图

Duplicate disk: recommended system - negative sampling strategy

Sequence traversal II of leetcode107 binary tree

How long can this bull market last Answers to questions 2021-05-11

The mobile version of Duoyu security browser will add new functions to make users browse more personalized

VMware ESXI7.0版本的安装与配置

Binary tree -- 257. All paths of binary tree

CyclicBarrier
随机推荐
NVIDIA programmable reasoning accelerator tensorrt learning notes (III) -- Accelerating reasoning
Binary tree - 404. Sum of left leaves
12.神经网络模型
合肥提前批
Get JD product details original data API
SHIB(柴犬币)一月涨幅数百倍,百倍币需具备哪些核心要素?2021-05-09
MySQL——主从复制
FreeRTOS个人笔记-信号量
The items of listview will be displayed completely after expansion
网站服务器停止响应是什么意思?
Stack and queue - 150. Inverse Polish expression evaluation
NVIDIA可编程推理加速器TensorRT学习笔记(三)——加速推理
这一次,彻底弄懂 Promise 原理
What are the precautions for using MySQL index? (answer from six aspects)
Stm32 systeminit trap during simulation debugging
链表相关方法
Prometheus operation and maintenance tool promtool (II) query function
京东按关键字搜索商品 API 的使用说明
J9 number theory: what is Dao mode? Obstacles to the development of Dao
Unified handling of global exceptions