Task 1: Max Odd Binary
"Make It Odd, Make It Big!"
This week's first task involves rearranging bits in a binary string to form the maximum odd binary number. Given a binary string containing at least one '1', we need to rearrange the bits to produce the largest possible odd binary number.
The Strategy: To create the maximum odd binary number, we need to place as many '1's as possible in the most significant positions while ensuring the number remains odd. Since an odd binary number must have '1' as its least significant bit, we put one '1' at the end and all other '1's at the beginning. The remaining zeros fill the middle positions.
Perl Implementation
sub max_odd_binary {
my ($bin) = @_;
die "Input must contain at least one '1'\n" unless $bin =~ /1/;
my $ones = () = $bin =~ /1/g;
my $zeros = length($bin) - $ones;
# Result: ($ones-1) '1's, then zeros, then one '1' at the end
return ('1' x ($ones - 1)) . ('0' x $zeros) . '1';
}
Python Implementation
def max_odd_binary(bin_str: str) -> str:
"""
Return maximum odd binary number by rearranging bits.
Args:
bin_str: Binary string containing at least one '1'.
Returns:
Maximum odd binary number as a string.
Raises:
ValueError: If input doesn't contain at least one '1'.
"""
if '1' not in bin_str:
raise ValueError("Input must contain at least one '1'")
ones = bin_str.count('1')
zeros = len(bin_str) - ones
# Result: (ones-1) '1's, then zeros, then one '1' at the end
return '1' * (ones - 1) + '0' * zeros + '1'