# Most worth with no 3 consecutive set bits

0
8

Given a non-negative integer n, discover the utmost worth that may be obtained by unsetting any set bit, such that no three consecutive bits within the ensuing integer are set bits.

Examples:

Enter: n = 2
Output: 2
Rationalization: 2’s binary kind is 10, no 3 consecutive set bits are right here. So, 2 itself can be reply.

Enter: n = 7
Output: 6
Rationalization: 7’s binary kind is …..00111.We are able to observe that 3 consecutive bits are set bits. This isn’t allowed. So, we are able to carry out operation of adjusting set bit to unset bit. Now, the quantity turns into 6 that’s …..00110. It satisfies the given situation. Therefore, the utmost attainable worth is 6.

Strategy: To resolve the issue comply with the beneath concept:

The thought is to first convert the given question into binary kind after which traverse over the binary type of the question and test if 3 consecutive bits are set(1) then convert the rightmost little bit of consecutive bit as unset(0) as a result of we wish most worth on the finish, for this now we have to unset least vital bit which is current on the rightmost aspect.

Beneath are the steps for the above strategy:

• Initialize an array set[] to 0, of dimension 35 to retailer the binary type of the given question.
• Covert the given question into binary kind and retailer it within the array set[].
• Run a loop from j = 30 until j ≥ 0,
• if ((1 << j) & n), set[j] = 1.
• Initialize a variable say fin_ans to retailer the reply.
• Now run a loop over the set[] array from probably the most vital bit in direction of the least vital bit.
• Examine if the ith bit and (i-1)th bit is about then unset the (i-2)th bit in order that 3 consecutive bit should not be set.
• if (set[j] == 1), fin_ans |= (1 << j).
• if (set[j – 1] == 1), set[j – 2] = 0.
• And in addition take the bitwiseOR operation with reply and a couple ofi, so as to add the all set bit values.
• if (set == 1), fin_ans |= 2.
• if (set == 1), fin_ans |= 1.
 `#embrace ` `utilizing` `namespace` `std;` ` `  `int` `noConseBits(``int` `n)` `{` `    ``int` `set;` ` `  `    ``for` `(``int` `j = 0; j < 35; j++)` `        ``set[j] = 0;` ` `  `    ``for` `(``int` `j = 30; j >= 0; j--) {` `        ``if` `((1 << j) & n) {` `            ``set[j] = 1;` `        ``}` `    ``}` `    ``int` `fin_ans = 0;` `    ``for` `(``int` `j = 30; j >= 2; j--) {` `        ``if` `(set[j] == 1) {` `            ``fin_ans |= (1 << j);` `            ``if` `(set[j - 1] == 1) {` `                ``set[j - 2] = 0;` `            ``}` `        ``}` `    ``}` `    ``if` `(set == 1)` `        ``fin_ans |= 2;` `    ``if` `(set == 1)` `        ``fin_ans |= 1;` ` `  `    ``return` `fin_ans;` `}` ` `  `int` `principal()` `{` `    ``int` `n = 7;` `    ``int` `ans = noConseBits(n);` ` `  `    ` `    ``cout << ans;` `    ``return` `0;` `}`