[leetcode] 231.Power of Two
来源:互联网 发布:部落冲突弓箭升级数据 编辑:程序博客网 时间:2024/05/19 21:16
题目:
Given an integer, write a function to determine if it is a power of two.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
题意:
判断一个数是否是2的指数倍。
思路:
考虑特殊情况n<=0,不是2的指数倍,1是的。
采用递归的方法,如果n%2!=0说明不是指数。否则递归查看n/2是不是。
以上。
代码如下:
class Solution {public: bool isPowerOfTwo(int n) { if(n == 0)return false; else if(n == 1)return true; else if(n % 2 != 0)return false; else return isPowerOfTwo(n/2); }};
当然,这是最简单的思路,另外我们可以考虑一个数字组成,如果该数字大于0,并且是2的指数倍的话,那么这个数字可以表示成这样的二进制数,00000…00100…000,只有第k位上是1,其余位都是0。那么这个数字减去1之后,1到k-1位上是1,其余位是1,即00000..00011…111,所以观察可得n&(n-1) 等于0。
以上。
代码如下:
class Solution {
public:
bool isPowerOfTwo(int 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
- 231. Power of Two LeetCode
- [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
- #leetcode#231. Power of Two
- 231.[Leetcode]Power of Two
- Leetcode 231. Power of Two
- [Objective-C] 目标文件反编译得到Objecitve-C源文件
- 初学stm32-环境搭建——stm32和IAR配置
- hdu - 4511 小明系列故事——女友的考验(AC自动机+DP)
- esper 常用类
- hdu4508解题报告
- [leetcode] 231.Power of Two
- java中创建对象的几种方法
- Linux下 git添加 key
- ActiveAndroid.initialize使用笔记
- jquery 表单 清空
- kindle3折腾之修砖、修复“wifi unavailable”等总结
- Servlet 3 + Spring MVC零配置:去除所有xml
- C/C++ 字节序/位域(Bit-fields)之我见
- ArcGIS文件(arcgis_js_api)部署相关问题总结