LeetCode之231,Power of Two——新学到的超快速简洁判别方法
来源:互联网 发布:ubuntu 限制root登录 编辑:程序博客网 时间:2024/06/05 09:29
数论的又一个又简单但是骚的不行的题,有点像一道菜:番茄炒蛋,谁都会炒,但是,如何炒的好吃,入口即惊艳,是非常困难的。
就我这智商,必须得先学人家怎么写,所以,学到了一个新奇的判定方法。
原题是这样的:
Given an integer, write a function to determine if it is a power of two.
描述的很简单吧?嗯,下面来看一种判定方法:
按位 与 操作
n&(n-1),比如,4的二进制是100,4-1,也就是3的二进制是011,4和3的二进制按位与操作是000
然后,这样一个n&(n-1)的结果判断一下是否等于==0,就可确定是不是2的幂次了。
所以结果就是:
return ((n&(n-1))==0)
所以,代码就是:
class Solution {public: bool isPowerOfTwo(int n) { if(n<=0) { return false; } return ((n&(n-1))==0); }};
0 0
- LeetCode之231,Power of Two——新学到的超快速简洁判别方法
- LeetCode之Power of Two
- leetcode 之 power of two
- leetcode之Power of Two
- leetcode之Power of Two
- LeetCode之Power of Two
- Leetcode——231. Power of Two
- leetcode——231—— Power of Two
- leetcode-231 Power of Two
- leetcode 231:Power of Two
- LeetCode 231: Power of Two
- leetcode 231: Power of Two
- leetcode[231]:Power of Two
- Power of Two(leetcode 231)
- leetcode-231-Power of Two
- LeetCode 231 Power of Two
- leetCode #231 Power of Two
- leetcode 231: Power of Two
- 7月29日--javascript进阶篇4
- 7月30日--javascript进阶篇后续
- 7月31日--旋转木马幻灯片
- 8月6号--时光轴
- GStreamer基础教程10——GStreamer工具
- LeetCode之231,Power of Two——新学到的超快速简洁判别方法
- sso(单点登录一)
- rpm安装器 参数
- 最好的Angular2表格控件
- RxBus
- Spring Boot配置文件乱码的问题
- 我的2017-搭建个人网站,确定后台语言(1)
- linux安装jdk 1.8
- 获得软键盘高度 监听软键盘