Challenge - 5 Problems
Set Bits Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Brian Kernighan's Set Bits Count
What is the output of the following Java code that counts set bits using Brian Kernighan's algorithm?
DSA Java
public class Main { public static int countSetBits(int n) { int count = 0; while (n > 0) { n = n & (n - 1); count++; } return count; } public static void main(String[] args) { System.out.println(countSetBits(29)); } }
Attempts:
2 left
💡 Hint
Count how many times the loop runs by removing the rightmost set bit each time.
✗ Incorrect
29 in binary is 11101 which has 4 set bits. Brian Kernighan's algorithm removes one set bit per iteration, so the count is 4.
❓ Predict Output
intermediateResult of Counting Set Bits for Zero
What will be the output when the input number is zero?
DSA Java
public class Main { public static int countSetBits(int n) { int count = 0; while (n > 0) { n = n & (n - 1); count++; } return count; } public static void main(String[] args) { System.out.println(countSetBits(0)); } }
Attempts:
2 left
💡 Hint
Zero has no set bits in binary.
✗ Incorrect
Since 0 has no set bits, the loop never runs and count remains 0.
🔧 Debug
advancedIdentify the Error in Set Bits Counting Code
What error will occur when running this code to count set bits?
DSA Java
public class Main { public static int countSetBits(int n) { int count = 0; while (n != 0) { n = n & (n + 1); count++; } return count; } public static void main(String[] args) { System.out.println(countSetBits(2)); } }
Attempts:
2 left
💡 Hint
Check the bitwise operation inside the loop and how it affects n.
✗ Incorrect
Using n & (n + 1) does not clear the rightmost set bit and can cause n to never become zero, leading to an infinite loop.
🧠 Conceptual
advancedWhy Brian Kernighan's Algorithm is Efficient
Why is Brian Kernighan's algorithm more efficient than checking each bit individually to count set bits?
Attempts:
2 left
💡 Hint
Think about how many times the loop runs compared to the number of bits in the number.
✗ Incorrect
Brian Kernighan's algorithm reduces the number by removing one set bit each iteration, so it runs only as many times as there are set bits, making it faster than checking all bits.
❓ Predict Output
expertOutput of Counting Set Bits for Negative Number
What is the output of the following code when counting set bits of -1 in Java?
DSA Java
public class Main { public static int countSetBits(int n) { int count = 0; while (n != 0) { n = n & (n - 1); count++; } return count; } public static void main(String[] args) { System.out.println(countSetBits(-1)); } }
Attempts:
2 left
💡 Hint
Consider how negative numbers are represented in Java (32-bit two's complement).
✗ Incorrect
-1 in Java is represented as all 32 bits set to 1 in two's complement, so the count of set bits is 32.
