231. Power of Two
来源:互联网 发布:淘宝收藏的店铺在哪里 编辑:程序博客网 时间:2024/06/11 01:18
Given an integer, write a function to determine if it is a power of two.
s思路:
1. 是否指数,一看就是binary search的问题。
2. 还不一定是,自己想多了,就是bit manipulation.看是否n的二进制表达只有一个1即可!
3. 还看到网上的方法2:很妙,不用移位,直接用数学常识,判断是否只有一个1的方法,就是n&(n-1),简直太妙了!
class Solution {public: bool isPowerOfTwo(int n) { // while(n){ if(n&1) return (n>>1)==0; n>>=1; } return 0; }};//方法2:简单,top-down的做法,不考虑移位,直接做整体的与运算!class Solution {public: bool isPowerOfTwo(int n) { if(n<=0) return false; return !(n&(n-1)); }};
0 0
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- HDU 3529 舞蹈链之可重复覆盖
- 《InsideUE4》UObject(四)类型系统代码生成
- java网络编程
- 线程间通信常用的三种方法
- JAVA修饰符类型(public,protected,private,friendly)
- 231. Power of Two
- systemverilog语法(三)
- 8步走让你成为数据科学家
- Arduino - 继电器
- 《javascript设计模式与开发实践》阅读笔记(10)—— 组合模式
- can1--can初探
- 【推荐】网罗优秀的博客
- 在cenOS下安装apache出现-bash: /etc/init.d/httpd: 没有那个文件或目录
- linux进程管理命令