Skip to main content
Back to problems
#2864
Easy Algorithms

Maximum odd binary number

Math String Greedy
82.9% acceptance
Feb 25, 2026
834
34
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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn maximum_odd_binary_number(s: String) -> String {
    let ones = s.chars().filter(|&c| c == '1').count();
    // Place (ones-1) '1's at the front, then zeros, then one '1' at the end
    let zeros = s.len() - ones;
    format!("{}{}{}", "1".repeat(ones - 1), "0".repeat(zeros), "1")
  }
}