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
原创粉丝点击