Remove one bit from a binary number to get maximum value
Last Updated :
21 May, 2021
Given a binary number, the task is to remove exactly one bit from it such that, after it’s removal, the resultant binary number is greatest from all the options.
Examples:
Input: 110
Output: 11
As 110 = 6 in decimal,
the option is to remove either 0 or 1.
So the possible combinations are 10, 11
The max number is 11 = 3 in decimal.
Input:1001
Output: 101
Approach:
- Traverse the binary number from left to right.
- Find the least redundant 0 bit, as this bit will have the least effect on the resultant binary number.
- Skip this bit, or remove it.
- The rest of the bits give the maximum value binary number.
Below is the implementation of the above approach:
Program:
C++
#include <bits/stdc++.h>
using namespace std;
int printMaxAfterRemoval(string s)
{
bool flag = false ;
int n = s.length();
for ( int i = 0; i < n; i++) {
if (s[i] == '0' && flag == false ) {
flag = true ;
continue ;
}
else
cout << s[i];
}
}
int main()
{
string s = "1001" ;
printMaxAfterRemoval(s);
}
|
Java
import java.io.*;
class GFG {
static int printMaxAfterRemoval(String s)
{
boolean flag = false ;
int n = s.length();
for ( int i = 0 ; i < n; i++) {
if (s.charAt(i) == '0' && flag == false ) {
flag = true ;
continue ;
}
else
System.out.print( s.charAt(i));
}
return 0 ;
}
public static void main (String[] args) {
String s = "1001" ;
printMaxAfterRemoval(s);
}
}
|
Python3
def printMaxAfterRemoval(s):
flag = False
n = len (s)
for i in range ( 0 , n):
if s[i] = = '0' and flag = = False :
flag = True
continue
else :
print (s[i], end = "")
if __name__ = = "__main__" :
s = "1001"
printMaxAfterRemoval(s)
|
C#
using System;
class GFG
{
static int printMaxAfterRemoval(String s)
{
bool flag = false ;
int n = s.Length;
for ( int i = 0; i < n; i++)
{
if (s[i] == '0' && flag == false )
{
flag = true ;
continue ;
}
else
Console.Write(s[i]);
}
return 0;
}
static void Main()
{
String s = "1001" ;
printMaxAfterRemoval(s);
}
}
|
PHP
<?php
function printMaxAfterRemoval( $s )
{
$flag = false;
$n = strlen ( $s );
for ( $i = 0; $i < $n ; $i ++)
{
if ( $s [ $i ] == '0' && $flag == false)
{
$flag = true;
continue ;
}
else
echo $s [ $i ];
}
}
$s = "1001" ;
printMaxAfterRemoval( $s );
?>
|
Javascript
<script>
function printMaxAfterRemoval(s)
{
let flag = false ;
let n = s.length;
for (let i = 0; i < n; i++)
{
if (s[i] == '0' && flag == false )
{
flag = true ;
continue ;
}
else
document.write(s[i]);
}
return 0;
}
let s = "1001" ;
printMaxAfterRemoval(s);
</script>
|
Time Complexity: O(n)
Share your thoughts in the comments
Please Login to comment...