I came across the question in my title while practicing Leet code. I was to evaluate whether any given number N is a power of 2. So for example, 4 is a power of 2 because 2² = 4, and 16 is a power of 2 because 2⁴ = 16, but 7 is not a power of 2. I couldn’t think of an answer to this question, so I searched online.
There are actually many ways to approach this problem of determining whether a number is a power of 2, but my favorite one is to “count the number of 1s.” When represented in binary form, any number which is a power of 2 should have exactly one “1” in its string of 0s and 1s.
Let me show you:
2⁰=1 (000001)
2¹=2 (000010)
2²=4 (000100)
2³=8 (001000)
2⁴=16 (010000)
On the other hand, any number that isn’t a power of 2 would have more than one “1” in its binary string. For example, 7 in binary form is 00000111 (that’s three “1s”).
Therefore, the steps to solving this coding problem in JavaScript would be:
- Covert the number N (N being the target number you want to evaluate) from decimal to binary using N.toString(2)
- If there is exactly one “1” in the binary form of N, then N is a power of 2. If there are no “1”s or more than one “1”, then N is NOT a power of 2.