You are given a binary string s that contains at least one '1'.
You have to rearrange the bits in such a way that the resulting binary number is the maximum odd binary number that can be created from this combination.
Return a string representing the maximum odd binary number that can be created from the given combination.
Note that the resulting string can have leading zeros.
Example 1:
Input: s = "0110"
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".
Example 2:
Input: s = "100"
Output: "001"Explanation: Because there is just one '1', it must be in the last position. So the answer is "001".
Constraints:
1 <= s.length <= 100s consists only of '0' and '1'.s contains at least one '1'.Before attempting this problem, you should be comfortable with:
A binary number is odd if and only if its last bit is 1. To maximize the number, we want as many 1s as possible in the higher-order positions (leftmost).
We can sort the string in descending order to push all 1s to the front. Then, we swap one 1 to the last position to ensure the number is odd. Since we sorted in descending order, the rightmost 1 is easy to find.
1s come first).1 in the sorted array (it will be at the boundary between 1s and 0s).1 with the last character of the array.We do not actually need to sort. The optimal answer has a simple structure: place all but one 1 at the beginning, followed by all 0s, and end with a single 1.
We just need to count the 1s. If there are count ones, the result is (count - 1) ones, then (n - count) zeros, then one 1.
1s in the string.(count - 1) ones + (length - count) zeros + 1.We can rearrange the string in-place using a two-pointer technique similar to the partition step in quicksort. We move all 1s to the left side of the array, then swap one 1 to the last position.
This achieves the same result as sorting but with a single O(n) pass.
left pointer starting at 0. Iterate through the array with index i.s[i] == '1', swap s[i] with s[left] and increment left.1s are at positions 0 to left - 1.s[left - 1] with s[n - 1] to place one 1 at the end.The defining property of an odd binary number is that its least significant bit (last character) must be '1'. A common mistake is placing all 1s at the beginning without reserving one for the end, resulting in an even number. Always ensure exactly one '1' is placed at the last position.
When the input contains only a single '1', the only valid output is that '1' at the end with all '0's before it. Failing to handle this edge case (e.g., trying to place count - 1 ones when count is 1) can cause index errors or incorrect string construction.