【LeetCode】231 - Power of Two

Given an integer, write a function to determine if it is a power of two.

Solution:一个整数如果是2的整数次方,那么它的二进制表示中有且只有一位是1,而其他所有位都是0。把这个整数与这个整数减去1之后进行与运算,那么这个整数当中唯一的1会变为0,这个整数也变为0

1 class Solution {
2 public:
3     bool isPowerOfTwo(int n) {
4         if(n<=0)return false;
5         return !(n&(n-1));
6     }
7 };

 

posted @ 2015-07-27 23:04  irun  阅读(108)  评论(0编辑  收藏  举报