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 };
原文地址:https://www.cnblogs.com/Reindeer/p/5634352.html