Bit Manipulation & Modular Arithmetic Challenge

#100DaysOfLeetcode journey 🚀 Day 20/100 — Bit Manipulation & Modular Arithmetic! Today’s Problem: 1680. Concatenation of Consecutive Binary Numbers 🔹 The Goal: Given an integer $n$, concatenate the binary representations of numbers from $1$ to $n$ into a single string and return its decimal value modulo $10^9 + 7$. 🔹 The Insight: At first glance, this looks like a string problem, but building a massive binary string is a recipe for a Memory Limit Exceeded (MLE) error. The trick is to realize that when you "append" a new number $i$ to your current result, you are essentially shifting your current value to the left by the number of bits in $i$ and then adding $i$. 🔹 The Difficulty: The numbers grow exponentially. To keep things under control, we apply the property of modular arithmetic: $$(A + B) \pmod M = ((A \pmod M) + (B \pmod M)) \pmod M$$ The real challenge? Knowing when the "bit length" of your current number increases (e.g., when moving from 3 to 4, you go from 2 bits to 3 bits). ✨ Achievement: Successfully bypassed string manipulation entirely to create a pure mathematical $O(n)$ solution. 🔍 Steps followed: ✔ Bit-Width Tracking: Monitored when $i$ reached a power of 2 to increment the shift amount. ✔ Efficient Shifting: Used (ans << bitLength) | i to concatenate values at the bit level. ✔ Modular Discipline: Applied the modulo at every step to prevent integer overflow. 🔧 Complexity Analysis: Time Complexity: $O(n)$ Space Complexity: $O(1)$ Thirteen days in and the "bit-shifting" logic is starting to feel like second nature. Onward! 🛠️ #Java #DSA #LeetCode #CodingJourney #100DaysOfCode #BitManipulation #MathAlgorithms #SoftwareEngineer #Optimization

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories