examination questions
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
解题代码
class Solution { public: /* * @param n: An integer * @return: True or false */ bool checkPowerOf2(int n) { int t; int b; if (n == 1 || n == 2){ return true; } if (n <= 0){ return false; } while (true){ t = n / 2; b = n % 2; if (b == 0){ if (t == 2){ return true; } else{ n = t; } } else{ return false; } } } };