[Leetcode] 231. Power of Two 解题报告
来源:互联网 发布:35位网络作家排名 编辑:程序博客网 时间:2024/06/05 08:03
题目:
Given an integer, write a function to determine if it is a power of two.
思路:
2的幂的二进制表示有一个特点,就是除了最高位是1之外,其余的位置上都是0,依据这个特点,可以设计如下两个算法:
1、逐位判断:依次获取n的非最高位的值,一旦发现不是0,就返回false。这在算法实现上可以采用&和>>来实现。
2、一次判断:n & (n-1)的作用是将n的最低位上的1变成0。所以n是2的幂的充要条件就是 (n & (n - 1)) == 0。实现起来只需要一行代码。
不过大家需要注意,在C++中位操作的优先级比较低,所以记得加括弧^_^。
代码:
1、逐位判断:
class Solution {public: bool isPowerOfTwo(int n) { if (n <= 0) { return false; } while (n > 1) { if ((n & 1) != 0) { return false; } n = (n >> 1); } return true; }};
2、一次判断:
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 231. Power of Two 解题报告
- [Leetcode] 231. Power of Two 解题报告
- LeetCode-Power of Two-解题报告
- 【LeetCode】Power of Two 解题报告
- leetcode解题报告233——Power of Two
- [leetcode] 326. Power of Three 解题报告
- 326. Power of Three LeetCode解题报告
- [leetcode] 342. Power of Four 解题报告
- 【LeetCode】Power of Three 解题报告
- 【LeetCode】Power of Four 解题报告
- leetcode 342. Power of Four 解题报告
- LeetCode 326. Power of Three 解题报告
- leetcode解题报告-342. Power of Four
- [Leetcode] 326. Power of Three 解题报告
- [Leetcode] 342. Power of Four 解题报告
- [leetcode] 231.Power of Two
- LeetCode ||231. Power of Two
- Python学习笔记【四】——《python基础教程》:: 字典:当索引不好用时
- javaAES加密解密32位密钥
- AT&T衰落的原因
- vue常见问题解决办法(二)|warning:component lists rendered with v-for should have explicit keys
- jquery validate 验证不提示问题
- [Leetcode] 231. Power of Two 解题报告
- SVN 报错 sqlite[S11]: database disk image is malformed
- 安装tslib中遇到的错误:./autogen.sh: 4: autoreconf: not found
- 【特征工程】3 特征工程技术与方法
- Android Studio 使用git时如何找回被冲掉的代码
- java 调用 C# webapi
- Caused by: org.xml.sax.SAXException: Scanner State 24 not Recognized
- 详解μC/OS-II如何检测任务堆栈实际使用情况——即如何设置ucosii任务堆栈大小
- 2016年我国网络安全态势