Thinking process

What numbers are power of 2?

  • 0? false
  • negative? false
  • 1? true
  • 2? true
  • 6? false
  • 8? false

What are those bits look lie?

  • 2 => 10
  • 4 => 100
  • They all have only one bit that is 1

=>Count number of 1 bits

Mistakes

6 is not power of 2, so you can't repeatedly minus 2 and check whether it's equal to 0 at last

public class Solution {
    public boolean isPowerOfTwo(int n) {
        if (n <= 0) return false;
        int res = 0;
        for (int i = 0; i < 32; ++i) {
            if ((n & (1 << i)) != 0) res++;
            if (res > 1) return false;
        }

        return true;
    }
}

Trick of n and n - 1

public class Solution {
    public boolean isPowerOfTwo(int n) {
        return (n > 0 && (n & (n - 1)) == 0);
    }
}

results matching ""

    No results matching ""