231. Power of Two

题目:

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

答案

2的幂有两个特点:

  1)大于0

  2)二进制形式都是首位为1,其余位为0,因此n&(n-1)等于0

1 class Solution {
2 public:
3     bool isPowerOfTwo(int n) {
4         if(  n>0&&(!(n&(n-1)))  )
5         return true;
6         else
7         return false;
8     }
9 };

 

posted @ 2016-07-01 21:52  绵绵思远道  阅读(144)  评论(0编辑  收藏  举报