LeetCode June Challenge - Day 8

Problem: LeetCode June Challenge - Day 8

Ideas:

  1. n must be positive.
  2. The binary representation must have one and only one bit set to 1.

Solution:

class Solution {
public:
    bool isPowerOfTwo(int n) {
        if(n <= 0) return false;
        while(n && n % 2 == 0) n >>= 1;
        return (n>>1) == 0;
    }
};