Binary Gap Solution: LeetCode 868 with Bit Manipulation

🚀 Day 45 of #100DaysOfCode ✅ Solved: Binary Gap (LeetCode 868) Today’s problem was about finding the longest distance between two consecutive 1s in the binary representation of a number. 🔎 Problem Insight: Given a positive integer n, convert it into binary and calculate the maximum distance between adjacent 1s. 💡 Key Idea: Instead of converting the number into a string, we can directly use bit manipulation: Traverse each bit using n & 1 Track the position of the previous 1 Update the maximum distance whenever a new 1 is found ⚡ Optimized Python Solution (O(log n) time | O(1) space) Python Copy code class Solution: def binaryGap(self, n: int) -> int: last = -1 max_dist = 0 position = 0 while n > 0: if n & 1: if last != -1: max_dist = max(max_dist, position - last) last = position n >>= 1 position += 1 return max_dist 🧠 What I Learned: Bitwise operations can make solutions more efficient Always think beyond string conversion for binary problems Tracking positions smartly reduces extra space usage Consistency > Motivation 🔥 One problem at a time towards mastering Data Structures & Algorithms. #LeetCode #ProblemSolving #Python #BitManipulation #DSA

  • text

To view or add a comment, sign in

Explore content categories