标签:
Note:
1) * 2 is same as << 1, so the number contains only one bit that is 1, the rest of bits are 0.
2) n-1 sets all the bits after bit 1 from 0 to 1, and bit 1 to from 1 to 0
3) (n & (n-1)) always equal to 0 when n is power of 2
4) eg. 8(1000) &7(0111), 4(0100) &3(0011)
5) when n = 0, it suppose to return false, but it will return true.
class Solution { public: /* * @param n: An integer * @return: True or false */ bool checkPowerOf2(int n) { // write your code here return n > 0 && (n & (n - 1)) == 0; } };
Here is a O(n) way:
class Solution { public: /* * @param n: An integer * @return: True or false */ bool checkPowerOf2(int n) { // write your code here int calculation = 0; for (int exp = 1; calculation < n; ++exp){ calculation << 1; if (calculation == n){ return true; } } return false; } };
标签:
原文地址:http://www.cnblogs.com/codingEskimo/p/5684163.html