142. O(1) Check Power of 2【easy】
Using O(1) time to check whether an integer n is a power of 2
.
Example
For n=4
, return true
;
For n=5
, return false
;
Challenge
O(1) time
解法一:
1 class Solution { 2 public: 3 /* 4 * @param n: An integer 5 * @return: True or false 6 */ 7 bool checkPowerOf2(int n) { 8 if (n > 0 && (n & n - 1) == 0) { 9 return true; 10 } 11 12 return false; 13 } 14 };