LeetCode Day 12: Binary Number Steps to One

Day 12/30 – LeetCode streak Today’s problem: Number of Steps to Reduce a Number in Binary Representation to One Rules are simple: if the number is even, divide by 2; if it’s odd, add 1. But doing this by simulating the whole number each time is slow and messy. The trick is to walk the binary string from right to left and just count how many operations each bit contributes, while carrying a 1 when we “add 1”: - Ignore index 0 (most significant bit); we stop at 'i > 0'. - For each bit, compute 'bit = (s.charAt(i) - '0') + carry'. - If 'bit' is '1', it’s effectively odd → we need '+1' then '/2' → 'steps += 2' and set 'carry = 1'. - If 'bit' is '0' or '2', it’s even → just '/2' → 'steps += 1', 'carry' stays as is. - After the loop, if there’s still a carry, add one more step because we effectively turned something like '"111"' into '"1000"' and need one last divide to reach '1'. Day 12 takeaway: Instead of repeatedly mutating the number, counting how many times each bit causes “+1 then /2” vs “just /2” gives an O(n), no-conversion solution that feels much cleaner once the carry idea clicks. #leetcode #dsa #java #bitmanipulation #consistency

  • graphical user interface

Keep going bud! Do graph too after a while They are not as difficult as people tend to believe All the best 😇

To view or add a comment, sign in

Explore content categories