Maximum Odd Binary Number

easy greedy string binary

Problem

You are given a binary string s containing at least one '1'. Rearrange its bits to form the maximum odd binary number possible. A binary number is odd only when its least significant (last) bit is '1', so exactly one '1' must sit at the end; to maximize the value, push every other '1' as far left as possible. Leading zeros are allowed.

Inputs = "0101"
Output"1001"
Two '1's: one is reserved for the last slot. The other '1' goes first, the two '0's fill the middle → "1001".

def maximumOddBinaryNumber(s):
    ones = s.count("1")          # how many 1-bits we have
    zeros = len(s) - ones        # the rest are 0-bits
    # Greedy layout: (ones-1) leading 1s, then all 0s,
    # then a single trailing 1 to make the number odd.
    return "1" * (ones - 1) + "0" * zeros + "1"
function maximumOddBinaryNumber(s) {
  let ones = 0;
  for (const ch of s) if (ch === "1") ones++;   // count 1-bits
  const zeros = s.length - ones;                 // the rest are 0s
  // (ones-1) leading 1s, all 0s, then one trailing 1 (odd).
  return "1".repeat(ones - 1) + "0".repeat(zeros) + "1";
}
String maximumOddBinaryNumber(String s) {
    int ones = 0;
    for (char ch : s.toCharArray()) if (ch == '1') ones++; // count 1s
    int zeros = s.length() - ones;                         // rest are 0s
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < ones - 1; i++) sb.append('1'); // leading 1s
    for (int i = 0; i < zeros; i++) sb.append('0');    // middle 0s
    sb.append('1');                                     // trailing 1 (odd)
    return sb.toString();
}
string maximumOddBinaryNumber(string s) {
    int ones = count(s.begin(), s.end(), '1'); // count 1-bits
    int zeros = s.size() - ones;               // rest are 0s
    // (ones-1) leading 1s, all 0s, then one trailing 1 (odd).
    return string(ones - 1, '1') + string(zeros, '0') + "1";
}
Time: O(n) Space: O(n)