Solved LeetCode problem using bit manipulation trick

✨ Day 5 of my LeetCode streak! Today I solved another interesting problem that taught me a cool bit manipulation trick 😎 💡 Problem: Smallest Number With All Set Bits Greater Than or Equal to N 📘 Statement: You are given a positive number n. Return the smallest number x greater than or equal to n, such that the binary representation of x contains only set bits (all 1s). Example: Input: n = 5 Output: 7 Explanation: Binary of 7 → 111 🧠 My Thought Process: At first, I noticed that numbers like 1 (1), 3 (11), 7 (111), 15 (1111) all have binary 1s only. So, the idea was simple 👇 Keep generating numbers like these (111...) until it becomes greater than or equal to n. To do that efficiently, I used bit manipulation: Start from mask = 1 Keep doing mask = (mask << 1) | 1 Stop when mask >= n The trick (mask << 1) | 1 means: Shift bits left (multiply by 2) Add one 1 at the end of the binary number 💻 Code (Java): class Solution { public int smallestNumber(int n) { int mask = 1; while (mask < n) { mask = (mask << 1) | 1; // shift left, add 1 at the end } return mask; } } 🧩 Example Dry Run: For n = 10: mask = 1 → 3 → 7 → 15 As soon as mask becomes 15 (>=10), that’s our answer ✅ Binary of 15 → 1111 🔍 Key Takeaways: Learnt how bit manipulation can make problems simpler and faster ⚡ Understood how left shift (<<) and bitwise OR (|) can be combined to create binary patterns Another cool use of binary logic to solve what looks like a simple math problem! 🗓️ LeetCode Streak: Day 5 / Consistency > Perfection 🔥 Every day I’m learning something new — one problem at a time. #LeetCode #100DaysOfCode #Java #BitManipulation #CodingJourney #ProblemSolving #Consistency

  • graphical user interface

To view or add a comment, sign in

Explore content categories