![]() |
VOOZH | about |
Given a number n, check whether every bit in the binary representation of the given number is set or not, if yes return true else return false.
Examples :
Input: n = 7
Output: true
Explanation: Binary for 7 is 111, all the bits are set so output is true.Input: n = 8
Output: false
Explanation: Binary for 8 is 1000, all the bits are not set so output is false.
Table of Content
The intuition is to check every bit one by one starting from the right. If any bit is 0 (not set), return false immediately. If you get through the whole number and every bit was 1, return true.
Consider the following dry run: n = 7, binary representation of 7 : 111
For n = 7 (111), (n & 1) = 1 ---> OK, right shift by 1 ---> n = 3 (011)
For n = 3(011), (n & 1) = 1 ---> OK, right shift by 1 ---> n = 1 (001)
For n = 1(001), (n & 1) = 1 ---> OK, right shift by 1 ---> n = 0(000)
Loop ends because n = 0, and no 0 bit encountered so returns true.
Final answer : true
true
The idea is that a number whose binary representation has all bits set (like 7 → 111, 15 → 1111) is always of the form 2^k - 1, where k is the number of set bits. So, we first count the number of set bits in the number. Let this count be k. Then we construct the number (2^k - 1), which is a number having exactly k bits set (like 111...k times). If the original number n is equal to (2^k - 1), it means all its bits are set. Otherwise, it is not.
Consider the following dry run : n = 7 ---> (111)
Step 1: n = 7 ---> n == 0? NO ---> continue
Step 2: Count set bits in the number n, (since 111 has 3 set bits) so count = 3
Step 3: (1 << count) = (1 << 3) = 8 ---> (1000)
Step 4: (1 << count) - 1 = 8 - 1 = 7 ---> (111)
Step 5: Compare n == 7 ---> TRUE
Step 6: return true
Final answer : true
true
The idea is that if a number n has all bits set in its binary representation (like 7 → 111), then adding 1 to it will produce a power of two (like 8 → 1000).
This happens because adding 1 to a sequence of all 1s causes a carry to propagate through all bits, turning them into 0s and adding a new leading 1. So, we compute x = n + 1 and then check whether x is a power of 2.
To check if a number is a power of 2, we use the condition (x & (x - 1)) == 0, which works because powers of 2 have exactly one bit set in binary.
Consider the following dry run : n = 7 --> (111)
Step 1: n = 7 ---> n <= 0? NO ---> continue
Step 2: x = n + 1 = 7 + 1 = 8 ---> (1000)
Step 3: x - 1 = 8 - 1 = 7 ---> (0111)
Step 4: (x & (x - 1)) = 1000 & 0111 = 0000 ---> equals 0
Step 5: return true
Final answer : true
true