Optimizing with Brian Kernighan's Algorithm

🔢 Day 47/75: Optimizing with Brian Kernighan’s Algorithm! Today’s challenge was counting the number of "1" bits in an integer. While the naive approach is to check all 32 bits one by one, I implemented a much more elegant solution known as Brian Kernighan’s Algorithm. The Logic: The expression n = n & (n - 1) has a fascinating property: it always flips the least significant set bit (the rightmost 1) to 0. By running this in a loop until $n$ becomes 0, the number of iterations equals exactly the number of set bits. If a number has only three "1" bits, the loop runs 3 times, not 32. The Result: ✅ Runtime: 0 ms (Beats 100.00% of Java users) ✅ Efficiency: $O(k)$ time complexity, where $k$ is the number of set bits. Mastering these bitwise shortcuts is what separates a good solution from a great one! 🚀 #75DaysOfCode #LeetCode #Java #BitManipulation #Algorithms #ComputerScience #Optimization #SoftwareEngineering

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories