"Day 78 - 100DaysOfCode: Minimum Bit Operations to Zero"

🚀 Day 78 - 100DaysOfCode 1611. Minimum One Bit Operations to Make Integers Zero Given an integer n, you must transform it into 0 using the following operations any number of times: Change the rightmost (0th) bit in the binary representation of n. Change the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0. Return the minimum number of operations to transform n into 0. Use a loop to find the largest power of 2 (curr) that is ≤ n. Keep track of its position k. This identifies the leftmost 1 bit in n. Mathematical Formula for Powers of Two: For numbers like 1, 2, 4, 8, 16... (i.e., 2^k), the number of operations to make them 0 is: f(k) = 2^(k + 1) - 1 Divide the Number: Split n into two parts: The most significant bit: curr = 2^k The remaining part: n' = n XOR curr (This removes the highest bit from n.) Recursive Relationship: The answer for n is derived as: A(n) = f(k) - A(n') Here, f(k) = steps to reduce 2^k → 0 A(n') = steps to reduce the smaller remaining number to 0 Why Subtraction (−) Instead of Addition (+): Because n is already partially reduced compared to 2^k. Those smaller bits represent “progress,” so we subtract the steps already covered. Recursion: The function calls itself with the smaller number n'. This continues until n becomes 0. Bitwise Operations Used: << → left shift to compute powers of two (2^(k+1)). ^ → XOR to remove the highest set bit from n. Complexity: Time: O((log n)²) Space: O(log n) (recursion depth) 📌 #100DaysOfCode #Day78 #Leetcode Good rated question

  • graphical user interface, text

To view or add a comment, sign in

Explore content categories