1: class Solution {
2: public:
3: bool isPowerOfTwo(int n) {
4: if (n <= 0) return false;
5: while (!(n & 1)) {
6: n >>= 1;
7: }
8: return !(n >> 1) ? true : false;
9: }
10: };
The following solution is inspired by counting number of ones in a integer.
1: class Solution {
2: public:
3: bool isPowerOfTwo(int n) {
4: return n > 0 && (n & (n - 1)) == 0;
5: }
6: };
No comments:
Post a Comment