Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Bitwise Algorithms
  • MCQs on Bitwise Algorithms
  • Tutorial on Biwise Algorithms
  • Binary Representation
  • Bitwise Operators
  • Bit Swapping
  • Bit Manipulation
  • Count Set bits
  • Setting a Bit
  • Clear a Bit
  • Toggling a Bit
  • Left & Right Shift
  • Gray Code
  • Checking Power of 2
  • Important Tactics
  • Bit Manipulation for CP
  • Fast Exponentiation
Open In App
Next Article:
Maximum XOR of Two Binary Numbers after shuffling their bits.
Next article icon

Remove one bit from a binary number to get maximum value

Last Updated : 21 May, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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:
 

  1. Traverse the binary number from left to right.
  2. Find the least redundant 0 bit, as this bit will have the least effect on the resultant binary number.
  3. Skip this bit, or remove it.
  4. The rest of the bits give the maximum value binary number.

Below is the implementation of the above approach:
Program: 
 

C++




// C++ program to find next maximum binary number
// with one bit removed
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum binary number
int printMaxAfterRemoval(string s)
{
    bool flag = false;
    int n = s.length();
 
    // Traverse the binary number
    for (int i = 0; i < n; i++) {
 
        // Try finding a 0 and skip it
        if (s[i] == '0' && flag == false) {
            flag = true;
            continue;
        }
        else
            cout << s[i];
    }
}
 
// Driver code
int main()
{
 
    // Get the binary number
    string s = "1001";
 
    // Find the maximum binary number
    printMaxAfterRemoval(s);
}
 
 

Java




// Java program to find next maximum binary number
// with one bit removed
 
import java.io.*;
 
class GFG {
  
// Function to find the maximum binary number
static int printMaxAfterRemoval(String s)
{
    boolean flag = false;
    int n = s.length();
 
    // Traverse the binary number
    for (int i = 0; i < n; i++) {
 
        // Try finding a 0 and skip it
        if (s.charAt(i) == '0' && flag == false) {
            flag = true;
            continue;
        }
        else
            System.out.print( s.charAt(i));
    }
  return 0;
}
 
// Driver code
    public static void main (String[] args) {
            // Get the binary number
    String s = "1001";
 
    // Find the maximum binary number
    printMaxAfterRemoval(s);
    }
}
// This code is contributed by anuj_67..
 
 

Python3




# Python3 program to find next maximum 
# binary number with one bit removed
 
# Function to find the maximum
# binary number
def printMaxAfterRemoval(s):
 
    flag = False
    n = len(s)
 
    # Traverse the binary number
    for i in range(0, n):
 
        # Try finding a 0 and skip it
        if s[i] == '0' and flag == False:
            flag = True
            continue
         
        else:
            print(s[i], end = "")
 
# Driver code
if __name__ == "__main__":
 
    # Get the binary number
    s = "1001"
 
    # Find the maximum binary number
    printMaxAfterRemoval(s)
 
# This code is contributed
# by Rituraj Jain
 
 

C#




// C# program to find next maximum
// binary number with one bit removed
using System;
 
class GFG
{
// Function to find the maximum
// binary number
static int printMaxAfterRemoval(String s)
{
    bool flag = false;
    int n = s.Length;
 
    // Traverse the binary number
    for (int i = 0; i < n; i++)
    {
 
        // Try finding a 0 and skip it
        if (s[i] == '0' && flag == false)
        {
            flag = true;
            continue;
        }
        else
            Console.Write(s[i]);
    }
    return 0;
}
 
 
// Driver Code
static void Main()
{
    // Get the binary number
    String s = "1001";
     
    // Find the maximum binary number
    printMaxAfterRemoval(s);
}
}
 
// This code is contributed by Ryuga.
 
 

PHP




<?php
// PHP program to find next maximum
// binary number with one bit removed
 
// Function to find the maximum
// binary number
function printMaxAfterRemoval($s)
{
    $flag = false;
    $n = strlen($s);
 
    // Traverse the binary number
    for ($i = 0; $i < $n; $i++)
    {
 
        // Try finding a 0 and skip it
        if ($s[$i] == '0' && $flag == false)
        {
            $flag = true;
            continue;
        }
        else
            echo $s[$i];
    }
}
 
// Driver code
 
// Get the binary number
$s = "1001";
 
// Find the maximum binary number
printMaxAfterRemoval($s);
 
// This code is contributed
// by Akanksha Rai
?>
 
 

Javascript




<script>   
    // Javascript program to find next maximum
    // binary number with one bit removed
     
    // Function to find the maximum
    // binary number
    function printMaxAfterRemoval(s)
    {
        let flag = false;
        let n = s.length;
 
        // Traverse the binary number
        for (let i = 0; i < n; i++)
        {
 
            // Try finding a 0 and skip it
            if (s[i] == '0' && flag == false)
            {
                flag = true;
                continue;
            }
            else
                document.write(s[i]);
        }
        return 0;
    }
     
    // Get the binary number
    let s = "1001";
       
    // Find the maximum binary number
    printMaxAfterRemoval(s);
     
</script>
 
 
Output: 
101

 

Time Complexity: O(n)
 



Next Article
Maximum XOR of Two Binary Numbers after shuffling their bits.

A

Abdullah Aslam
Improve
Article Tags :
  • Bit Magic
  • DSA
  • binary-string
Practice Tags :
  • Bit Magic

Similar Reads

  • Maximum number in Binary tree of binary values
    Given a binary tree consisting of nodes, each containing a binary value of either 0 or 1, the task is to find the maximum decimal number that can be formed by traversing from the root to a leaf node. The maximum number is achieved by concatenating the binary values along the path from the root to a
    6 min read
  • Smallest number whose set bits are maximum in a given range
    Given a positive integer 'l' and 'r'. Find the smallest number 'n' such that l <= n <= r and count of the number of set bits(number of '1's in binary representation) is as maximum as possible. Examples : Input: 1 4Output: 3Explanation:Binary representation from '1' to '4':110 = 0012210 = 01023
    9 min read
  • Maximum XOR of Two Binary Numbers after shuffling their bits.
    Given two n-bit integers a and b, find the maximum possible value of (a' xor b') where a' is a shuffle-a, b' is a shuffle-b and xor is the bitwise xor operator. Note: Consider a n-bit integer a. We call an integer a' as shuffle-a if a' can be obtained by shuffling the bits of a in its binary represe
    8 min read
  • Maximum XOR-value of at-most k-elements from 1 to n
    You are given two positive integer n and k. You have to calculate the maximum possible XOR value of at most k-elements from 1 to n. Note:k > 1Examples : Input : n = 7, k = 3 Output : 7 Explanation : You can select 1, 2, 4 for maximum XOR-value Input : n = 7, k = 2 Output : 7 Explanation : You can
    4 min read
  • Minimum Deci-Binary numbers required to obtain a given sum S
    Given a numeric string S representing a positive decimal integer, the task is to find the minimum number of positive Deci-Binary numbers required to obtain the sum S. Deci-Binary Numbers: Decimal numbers consisting of only 0s and 1s as its digits. Examples: Input: S = "31"Output: 3Explanation: S can
    5 min read
  • Minimize the maximum of 0s left or 1s deleted from Binary String
    You are given a binary string S of size N consisting of characters 0 and/or 1. You may remove several characters from the beginning or the end of the string. The task is to find the cost of removal where the cost is the maximum of the following two values: The number of characters 0 left in the stri
    8 min read
  • Generate all the binary number from 0 to n
    Given a positive integer number n generate all the binary number from 0 to n. Examples: Input : 5 Output : 0 1 10 11 100 101 Binary numbers are 0(0), 1(1), 2(10), 3(11), 4(100) and 5(101). Input : 10 Output : 0 1 10 11 100 101 110 111 1000 1001 1010 This program simple use predefined function (itoa(
    6 min read
  • Python Bin | Count total bits in a number
    Given a positive number n, count total bit in it. Examples: Input : 13 Output : 4 Binary representation of 13 is 1101 Input : 183 Output : 8 Input : 4096 Output : 13 We have existing solution for this problem please refer Count total bits in a number link. Approach#1: We can solve this problem quick
    3 min read
  • Maximum XOR of Two Numbers in an Array | Set 2
    Given an array arr[] consisting of N integers, the task is to find the maximum Bitwise XOR from all the possible pairs in the given array. Examples: Input: arr[] = {25, 10, 2, 8, 5, 3}Output: 28Explanation:The maximum result is 5^25 = 28. Input: arr[] = {1, 2, 3, 4, 5, 6, 7}Output: 7Explanation:The
    12 min read
  • Maximum number of set bits count in a K-size substring of a Binary String
    Given a binary string S of size N and an integer K. The task is to find the maximum number of set bit appears in a substring of size K. Examples: Input: S = "100111010", K = 3 Output: 3 Explanation: The substring "111" contains 3 set bits. Input:S = "0000000", K = 4 Output: 0 Explanation: S doesn't
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences