Given a binary string S, the task is to find the minimum number of Powers of 2 required to express a S.

Examples:

Input:_ S = “111”_

Output:_ 2_

Explanation:

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”_

Output:_ 4_

Explanation:

1101101 can be represented as 27 – 24 – 22 + 20.

Approach:

The key observation to solve this problem is that we can replace any consecutive sequence of 1 by using only two powers of 2.

Illustration:

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:

  • C++

filter_none

edit

play_arrow

brightness_4

// C++ Program to implement the

// above approach

#include <bits/stdc++.h>

**using** **namespace** std;

// Function to return the minimum

// distinct powers of 2 required

// to express s

**void** findMinimum(string s)

{

**int** n = s.size();

**int** x[n + 1] = { 0 };

// Reverse the string to

// start from lower powers

reverse(s.begin(), s.end());

**for** (``**int** i = 0; i < n; i++) {

// Check if the character is 1

**if** (s[i] == '1'``) {

**if** (x[i] == 1) {

x[i + 1] = 1;

x[i] = 0;

}

// Add in range provided range

**else** **if** (i and x[i - 1] == 1) {

x[i + 1] = 1;

x[i - 1] = -1;

}

**else**

x[i] = 1;

}

}

// Initialize the counter

**int** c = 0;

**for** (``**int** i = 0; i <= n; i++) {

// Check if the character

// is not 0

**if** (x[i] != 0)

// Increment the counter

c++;

}

// Print the result

cout << c << endl;

}

// Driver Code

**int** main()

{

string str = "111"``;

findMinimum(str);

**return** 0;

}

Output:

2

#arrays #competitive programming #greedy #mathematical #strings #binary-string #substring

Minimum number of distinct powers of 2 required to express a given binary number
1.25 GEEK