Minimize given flips required to reduce N to 0
Given an integer N, the task is to reduce the value of N to 0 by performing the following operations minimum number of times:
- Flip the rightmost (0th) bit in the binary representation of N.
- If (i – 1)th bit is set, then flip the ith bit and clear all the bits from (i – 2)th to 0th bit.
Input: N = 3
The binary representation of N (= 3) is 11
Since 0th bit in binary representation of N(= 3) is set, flipping the 1st bit of binary representation of N modifies N to 1(01).
Flipping the rightmost bit of binary representation of N(=1) modifies N to 0(00).
Therefore, the required output is 2
Input: N = 4
Approach: The problem can be solved based on the following observations:
1 -> 0 => 1
10 -> 11 -> 01 -> 00 => 2 + 1 = 3
100 -> 101 -> 111 -> 110 -> 010 -> … => 4 + 2 + 1 = 7
1000 -> 1001 -> 1011 -> 1010 -> 1110 -> 1111 -> 1101 -> 1100 -> 0100 -> … => 8 + 7 = 15
Therefore, for N = 2N total (2(N + 1) – 1) operations required.
If N is not a power of 2, then the recurrence relation is:
MinOp(N) = MinOp((1 << cntBit) – 1) – MinOp(N – (1 << (cntBit – 1)))
cntBit = total count of bits in binary representation of N.
MinOp(N) denotes minimum count of operations required to reduce N to 0.
Follow the steps below to solve the problem:
- Calculate the count of bits in binary representation of N using log2(N) + 1.
- Use the above recurrence relation and calculate the minimum count of operations required to reduce N to 0.
Below is the implementation of the above approach.
Time Complexity: O(log(N))
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.