Leetcode 231题Power of Two
来源:互联网 发布:c语言 贪吃蛇 编辑:程序博客网 时间:2024/06/05 23:56
Leetcode 231题Power of Two
题目
Given an integer, write a function to determine if it is a power of two.
即判断一个数是否是2的次方数 —— [ Power of Two ]
思路
如果一个数是2的次方数,那么n用二进制表示的数只有一位上是1,其他位上都是0,例如100000,0010,0001等,那么n-1就表达为例如,011111,0001,0000。那么可以发现n和n-1按位于的结果一定为零。
如果n不是2的次方数,那么用二进制表示的数不只有一个位上是1,例如0101,那么n-1的结果为0100,n和n-1的按位于结果一定不是零。
解法
- C语言
bool isPowerOfTwo(int n) { return n>0 && ((n & (n-1)) == 0);}
- C++
class Solution {public: bool isPowerOfTwo(int n) { return n>0 && ((n & (n-1)) == 0); }};
- Javascript
/** * @param {number} n * @return {boolean} */var isPowerOfTwo = function(n) { return n>0 && ((n & (n-1)) == 0); };
0 0
- 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
- 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
- [Leetcode]#231 Power of Two
- Leetcode #231 Power of Two
- [LeetCode 231] Power of Two
- [leetcode 231]Power of Two
- 周公解梦api 根据梦到的事物解梦
- Java Classloader机制解析
- 二叉树构建与遍历
- 连续特征离散化达到更好的效果,特征选择的工程方法
- 系统级搜索(基础应用)-CSSearchable
- Leetcode 231题Power of Two
- 数据库表和字段名命名规则
- angularJS学习之路(九)---ng-if
- AngularJS Form 进阶:远程校验和自定义输入项
- C# 类的继承
- Spring task quartz 定时任务的几种实现
- 第十章 组合与继承
- Linux-.a、.so和.o文件
- 怎样看待 12 个月内自学完成 4 年麻省理工学院计算机科学的 33 门课程的 Scott H. Young 所谓的超速学习理论和方法(费曼技巧)以及背后「Get More from Life」的理念