Given a binary string S, the task is to find the minimum number of Powers of 2 required to express a S.
Input: S = “111”
Two possible representations of “111” (= 7) using powers of 2 are:
20 + 21 + 22 = 1 + 2 + 4 = 7
23 – 20 = 8 – 1 = 7
Therefore, the minimum powers of 2 required to represent S is 2.
Input: S = “1101101”
1101101 can be represented as 27 – 24 – 22 + 20.
The key observation to solve this problem is that we can replace any consecutive sequence of 1 by using only two powers of 2.
S = “1001110”
The sequence of 3 consecutive 1’s, “1110” can be expressed as 24 – 21
Therefore, the given str
Follow the steps below to solve the problem:
- Reverse the string S.
- Iterate over the string S.
- Replace every substring of 1’s lying within indices [L, R] by placing 1 at R+1 and -1 at L.
- Once the entire string is traversed, count the number of non-zero values in the string as the required answer.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(N)
- Minimum number of given powers of 2 required to represent a number
- Minimum number of palindromes required to express N as a sum | Set 1
- Minimum number of palindromes required to express N as a sum | Set 2
- Distinct powers of a number N such that the sum is equal to K
- Powers of 2 to required sum
- Minimum number of segments required such that each segment has distinct elements
- Minimum given operations required to convert a given binary string to all 1's
- Minimum operations required to make all the elements distinct in an array
- Find minimum changes required in an array for it to contain k distinct elements
- Minimum cost to form a number X by adding up powers of 2
- Count of minimum reductions required to get the required sum K
- Minimum number of operations required to obtain a given Binary String
- Split N powers of 2 into two subsets such that their difference of sum is minimum
- Minimum jumps required to group all 1s together in a given Binary string
- Minimum flips required to form given binary string where every flip changes all bits to its right as well
- Balance pans using given weights that are powers of a number
- Number of triangles possible with given lengths of sticks which are powers of 2
- Find all powers of 2 less than or equal to a given number
- Minimum number of steps required to obtain the given Array by the given operations
- Print all integers that are sum of powers of two given numbers
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.