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.
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".
To get the maximum odd binary number, we want as many ‘1’s as possible at the left (most significant bits), but the last bit must be ‘1’ (to make it odd). So, put all ‘1’s except one at the front, all ‘0’s after, and one ‘1’ at the end.
classSolution {
public String maximumOddBinaryNumber(String s) {
int ones = 0;
for (char c : s.toCharArray()) if (c =='1') ones++;
int zeros = s.length() - ones;
StringBuilder sb =new StringBuilder();
for (int i = 0; i < ones - 1; i++) sb.append('1');
for (int i = 0; i < zeros; i++) sb.append('0');
sb.append('1');
return sb.toString();
}
}