๐ช Step 1: My Initial Solution โ Converting to Binary
My first thought was:
A number is a power of two only if its binary representation contains exactly one โ1โ.
So I wrote a function to convert a number to its binary form and then counted how many 1s it had.
class Solution {
public:
string set_bit(int num){
if (num == 0) return "0";
string bin = "";
while (num > 0){
int rem = num % 2;
bin += to_string(rem);
num = num / 2;
}
return bin; // binary in reverse order
}
bool isPowerOfTwo(int n) {
string bits = set_bit(n);
int count = 0;
for (int i = 0; i < bits.length(); i++){
if (bits[i] == '1') count++;
}
return count == 1;
}
};
It worked! Even though the binary string is reversed, it didnโt matter since I only cared about the number of 1s.
โ
What I Learned:
- How to convert a number to binary using %
- How to analyze the number of set bits (1s).
๐ง Step 2: A Cleaner Way โ Count Set Bits Without Strings
While reviewing other solutions, I realized I didnโt need to build a binary string at all. I could count the set bits directly while dividing the number.
Hereโs the improved solution:
class Solution {
public:
bool isPowerOfTwo(int n) {
if (n <= 0) return false;
int count = 0;
while (n > 0) {
if (n % 2 == 1) count++; // count set bits
n /= 2;
}
return count == 1;
}
};
Much better! This avoids unnecessary string manipulation and directly counts the 1s.
๐ฅ Step 3: The Most Efficient Way โ Bit Manipulation Trick
Finally, I stumbled upon this line of genius:
return n > 0 && (n & (n - 1)) == 0;
This is the most optimized and elegant solution to check if a number is a power of two. Butโฆ how does it work?
๐ How n & (n - 1) == 0 Works
Example 1:
n = 8 โ binary = 1000
n - 1 = 7 โ binary = 0111
so (8&7)==0 is true,
and 8>0 is also true ie n > 0 && (n & (n - 1)) gives 1. โ
result is 1 โ so 8 is a power of 2
Example 2:
n = 6 โ binary = 1100
n - 1 = 5 โ binary = 1010
so (6&5)==0 is false,
and 6>0 is true ie n > 0 && (n & (n - 1)) gives 0. โ
result is 0 โ so 6 is not a power of 2
๐ง Why This Works:
A power of two has exactly one set bit. Subtracting 1 from it flips that bit and all bits to the right of it.
So n & (n - 1) results in 0 only if n had just one set bit.
Hereโs the final optimized version:
class Solution {
public:
bool isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0;
}
};
Top comments (0)