Maximum Odd Binary Number

Updated on 17 June, 2025
Maximum Odd Binary Number header image

Problem Statement

You are provided with a binary string s that includes at least one character '1'. Your task is to rearrange the characters of the string to form the largest possible odd binary number. An odd binary number is characterized by having its least significant bit (the rightmost bit) set to '1'. After rearranging, the new binary sequence should represent the highest value possible under these conditions and it should be returned as the output string. This maximum rearrangement may include leading zeros, which are generally non-consequential in numerical values but must be preserved in the string output format.

Examples

Example 1

Input:

s = "010"

Output:

"001"

Explanation:

Because there is just one '1', it must be in the last position. So the answer is "001".

Example 2

Input:

s = "0101"

Output:

"1001"

Explanation:

One of the '1's must be in the last position. The maximum number that can be made with the remaining digits is "100". So the answer is "1001".

Constraints

  • 1 <= s.length <= 100
  • s consists only of '0' and '1'.
  • s contains at least one '1'.

Approach and Intuition

To generate the maximum odd binary number from a given binary string:

  1. Identify the count of '1's and '0's in the string.

    • Frequency of '1's determines how many times the bit '1' can be placed in the result.
    • Frequency of '0's will dictate the placement of zero bits.
  2. Construct the binary number:

    • To maximize the number, prioritize the placement of '1's on the left side. This is because in binary notation, the leftmost bits have the highest value.
    • Ensure that the last bit (rightmost) is '1' to make the number odd.
    • Fill the middle bits with '0's as required.
  3. Examples walkthrough:

    • For s = "010", the goal is to get the maximum sequence that ends in '1'. Placing the single '1' at the end yields "001".
    • For s = "0101", with two '1's available, place one '1' at the end for oddness and the other at the foremost available position. This offers "1001" as the maximum odd binary number.

By following these steps, we rearrange the bits efficiently to maximize the value of the binary number ending in '1'. This guarantees that the result is the largest possible odd binary number that can be formed from the input string.

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
public:
    string findMaxOddBinary(string binary) {
        // Initiate the length and character buffer
        const int len = binary.size();
        char* buffer = new char[len + 1];
        strcpy(buffer, binary.c_str());

        // Pointers for binary traversal
        int start = 0;
        int end = len - 1;

        while(start <= end) {
            // Move start pointer if element is '1'
            if (buffer[start] == '1') {
                start++;
            }
            // Move end pointer if element is '0'
            if (buffer[end] == '0') {
                end--;
            }
            // Swap logic for mismatched pair
            if (start <= end && buffer[start] == '0' && buffer[end] == '1') {
                buffer[start] = '1';
                buffer[end] = '0';
            }
        }

        // Set the highest possible odd binary value
        buffer[start - 1] = '0';
        buffer[len - 1] = '1';

        return buffer;
    }
};

The provided C++ solution manipulates a binary string to find the maximum odd binary number. The method findMaxOddBinary takes a binary string as input and manipulates it directly using a character buffer.

  • The function first converts the string input into a character array.
  • Using two pointers, start and end, the function iterates from both ends of the array towards the center.
  • It increments the start pointer for every '1' encountered and decrements the end pointer for every '0'.
  • When a '0' at the start pointer and a '1' at the end pointer are encountered, they are swapped.
  • After rearranging the characters, the function ensures the binary number is odd by setting the last character to '1'. The character just before the start pointer remains '0', implying cutting at a point that yields the highest odd binary number.
  • The function returns this modified character buffer as the resulting string, representing the highest odd binary number achievable from the original input.
java
class Solution {
    public String findLargestOddBinary(String binary) {
        // Convert string to character array
        char[] characters = binary.toCharArray();
        int length = characters.length;
        
        // Define boundaries for processing
        int start = 0;
        int end = length - 1;

        while (start <= end) {
            
            // Move start pointer if it's on '1'
            if (characters[start] == '1') {
                start++;
            }
            // Move end pointer if it's on '0'
            if (characters[end] == '0') {
                end--;
            }
            // Switch elements if they are out of order and positions are valid
            if (start <= end && characters[start] == '0' && characters[end] == '1') {
                characters[start] = '1';
                characters[end] = '0';
            }
        }

        // Ensure the largest binary number with an odd decimal value
        characters[start - 1] = '0';
        characters[length - 1] = '1';

        return new String(characters);
    }
}

The Java solution provided aims to modify a binary string to produce the largest possible odd binary number. Here's an explanation of how the code functions:

  1. The binary string is converted into a character array to facilitate manipulation of individual bits.

  2. Two pointers, start and end, are initialized to traverse from the beginning and the end of the array respectively.

  3. The main loop continues until start exceeds end. Inside the loop:

    • The code increments the start pointer if it points to a '1' to skip over unchanged bits.
    • It decrements the end pointer if it's pointing to a '0' to find a '1' that can be swapped.
  4. A condition inside the loop checks if start is less than or equal to end and if characters[start] is '0' and characters[end] is '1'. If true, it switches these characters to maintain the largest binary number. This step essentially "pushes" all the '1' bits towards the front of the string.

  5. After the loop, to ensure the number is odd, the code sets the last bit of the binary string (characters[length - 1]) to '1' and modifies the bit at start - 1 to '0' to ensure the integrity of prior reordering.

The method finally returns the newly constructed string which represents the largest odd binary number that can be formed from the input string.

This approach ensures the resulting binary number retains maximum possible value while being odd, which is crucial for certain computational optimizations or specific domain requirements where binary odd numbers might be of significance.

python
class Solution:
    def maxOddBinaryNum(self, binary_str: str) -> str:
        length = len(binary_str)
        characters = list(binary_str)

        start = 0
        end = length - 1
        while start <= end:
            if characters[start] == '1':
                start += 1
            if characters[end] == '0':
                end -= 1
            if start <= end and characters[start] == '0' and characters[end] == '1':
                characters[start], characters[end] = '1', '0'
        
        characters[start - 1] = '0'
        characters[length - 1] = '1'

        return "".join(characters)

This Python solution involves modifying a string representing a binary number to find the maximum odd binary number by rearranging its digits.

  • The function maxOddBinaryNum initializes by determining the length of the string and converting it into a list for mutable operations.
  • Begin by setting pointers at the start and the end of the list.
  • Use a while loop to check conditions from both ends of the list:
    • If the character at the start is '1', increment the start pointer.
    • If the character at the end is '0', decrement the end pointer.
    • Swap '0' at the start with '1' at the end to move '1's towards the end and '0's towards the start.
  • The first '1' from the start is changed to '0', and the last character of the list is set to '1', ensuring the result is an odd binary number.
  • Join the characters to form the resulting binary string and return it.

This approach ensures that:

  • The binary number remains within the highest possible order while still becoming odd.
  • Efficient swapping and condition checks ensure minimal computational overhead for large strings.

Comments

No comments yet.