判断一个数是不是2的幂,有三种方法

第一种,直接右移操作,看对2取模是否为1

代码如下

public class Solution {public boolean isPowerOfTwo(int n) {while (n > 1) {if (n % 2 != 0) return false;n /= 2;}return n == 1;}
}

第二种方法,统计二进制表示是位为1的个数,为1说明是2的幂

代码如下

public class Solution {public boolean isPowerOfTwo(int n) {int count = 0;for (int i = 0; i < 32; i++) {if ((n & (1 << i)) != 0) count++;}return n > 0 && count == 1;}
}

第三种,直接用n&(n-1) == 0来判断

代码如下

public class Solution {public boolean isPowerOfTwo(int n) {return n > 0 && (n & (n - 1)) == 0;}
}

LeetCode Power of Two相关推荐

  1. [LeetCode] Power of Two 判断2的次方数

    Given an integer, write a function to determine if it is a power of two. Example 1: Input: 1 Output: ...

  2. [LeetCode]Power

    周五的晚上,女朋友看爸爸去哪儿,电脑都是我的,狂刷LeetCode,做了十来题,最有印象的还是Power.题目如下: Implement pow(x, n).就是实现x的n次方. 这是一题很传统的题目 ...

  3. LeetCode : Power of Two

    Given an integer, write a function to determine if it is a power of two. class Solution { public:boo ...

  4. [LeetCode] Power of Four

    Given an integer (signed 32 bits), write a function to check whether it is a power of 4. Example: Gi ...

  5. LeetCode Power of Three

    题意:不用循环,判断一个数是否是3的幂 思路:通过判断指数是否是整数 注意用Math.log函数有的返回不正确,用Math.log10 代码如下: public class Solution {pub ...

  6. [leetcode] Power of Two 判断一个数是否是2的平方

    bool isPowerOfTwo(int n) {int count = 0;int i = 0;if(n < 0)return false;for(i = 0; i < sizeof( ...

  7. LeetCode 2156. 查找给定哈希值的子串(字符串哈希)

    文章目录 1. 题目 2. 解题 1. 题目 给定整数 p 和 m ,一个长度为 k 且下标从 0 开始的字符串 s 的哈希值按照如下函数计算: hash(s,p,m)=(val(s[0])∗p0+v ...

  8. [LeetCode][JavaScript]Power of Three

    Power of Three Given an integer, write a function to determine if it is a power of three. Follow up: ...

  9. leetcode python3 简单题231. Power of Two

    1.编辑器 我使用的是win10+vscode+leetcode+python3 环境配置参见我的博客: 链接 2.第二百三十一题 (1)题目 英文: Given an integer, write ...

最新文章

  1. docker打包镜像出现python安装包超时的现象
  2. c#使用System.Windows.Forms.DataVisualization.Charting.dll绘制图表实例
  3. powershell 常用命令笔记
  4. python 获取系统相关编码的函数
  5. Python type函数和isinstance函数区别 - Python零基础入门教程
  6. 三大运营商移动电话用户总数公布了 同比增长6.2%
  7. php ajax 长轮询 表单,Thinkphp结合AJAX长轮询实现PC与APP推送详解
  8. 使用hibernate可以优化的地方
  9. Spark Hive 云原生改造在智领云的应用
  10. Spring的XML解析原理,ie浏览器java插件下载
  11. GDAL源码剖析(九)之GDAL体系架构
  12. BRVAH(让RecyclerView变得更高效) (3)
  13. 生产排程系统_MES环境下如何执行智能生产排程
  14. Flutter 使用Dart Format格式化代码
  15. 用Excel做一个案例分析
  16. p1口实验_【正点原子FPGA连载】第二章 实验平台简介-摘自【正点原子】开拓者 FPGA 开发指南...
  17. 今天看到CSDN某博客提到的linux在线音乐播放器,移动的咪咕音乐不错,推荐一下
  18. 任正非:战略思想家的典范
  19. win10查看无线密码
  20. 微信小程序获取的微信头像模糊或者无法显示

热门文章

  1. 以下选项不是python打开方式的是-以下选项,不是Python保留字的选项是:_学小易找答案...
  2. python3.7.2教程-python 3.7极速入门教程2 Hello与变量
  3. python3菜鸟教程中文-我的python学习方法和资源整理,干货分享
  4. python学费多少-2020年10月徐州学python要多少学费
  5. python开发需要掌握哪些知识-Python基础进阶需要掌握哪些知识点?
  6. python批量读取csv文件-Python读取/批量读取文件
  7. python画曲线图例-如何使用python画曲线图
  8. python画折线图代码-python画折线示意图实例代码
  9. python工作好找吗-Python好找工作吗 不看会后悔
  10. python实现简单的api接口-Python 实现接口测试的简单实例