Python Bit Manipulation: Counting Set Bits with Brian Kernighan’s Algorithm

Day 59 of my #100DaysOfCode challenge 🚀 Today I implemented a Python program to count the number of set bits (1s) in a binary number. This uses an efficient bit manipulation technique and is very important in DSA & low-level optimization. What the program does: • Takes an integer n as input • Converts it conceptually to binary • Counts the number of set bits (1s) • Uses an optimized approach instead of checking each bit Example Outputs: 29 (11101) → 4 set bits 7 (111) → 3 set bits 16 (10000) → 1 set bit How the logic works: Uses Brian Kernighan’s Algorithm: n = n & (n - 1) • This removes the rightmost set bit in each step • Repeat until n = 0 • Count how many times this operation runs Why this is important: – Much faster than checking every bit ⚡ – Used in: Bit manipulation problems Competitive programming Low-level optimizations – Common in coding interviews Time Complexity: O(number of set bits) Space Complexity: O(1) Key Takeaways: – Understanding bitwise operations – Efficient counting techniques – Writing optimized solutions – Learning real-world low-level logic #100DaysOfCode #Day59 #Python #Programming #DSA #Algorithms #BitManipulation #Binary #CodingPractice #ProblemSolving #InterviewPrep #Optimization #DeveloperJourney #Consistency #BTech #CSE #AIandML #VITBhopal #TechJourney

  • text

To view or add a comment, sign in

Explore content categories