perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 367 - Task 1: Max Odd Binary

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-367/#TASK1
 3 #
 4 # Task 1: Max Odd Binary
 5 # ======================
 6 #
 7 # You are given a binary string that has at least one ‘1’.
 8 #
 9 # Write a script to rearrange the bits in such a way that the resulting binary
10 # number is the maximum odd binary number and return the resulting binary
11 # string. The resulting string can have leading zeros.
12 #
13 ## Example 1
14 ##
15 ## Input: $str = "1011"
16 ## Output: "1101"
17 ##
18 ## "1101" is max odd binary (13).
19 #
20 ## Example 2
21 ##
22 ## Input: $str = "100"
23 ## Output: "001"
24 ##
25 ## "001" is max odd binary (1).
26 #
27 ## Example 3
28 ##
29 ## Input: $str = "111000"
30 ## Output: "110001"
31 #
32 ## Example 4
33 ##
34 ## Input: $str = "0101"
35 ## Output: "1001"
36 #
37 ## Example 5
38 ##
39 ## Input: $str = "1111"
40 ## Output: "1111"
41 #
42 ############################################################
43 ##
44 ## discussion
45 ##
46 ############################################################
47 #
48 # We need one "1" at the end of the output, but all others go to the
49 # beginning to maximize the number. So we sort the digits by size,
50 # then move one "1" to the end.
51 
52 use v5.36;
53 
54 max_odd_binary("1011");
55 max_odd_binary("100");
56 max_odd_binary("111000");
57 max_odd_binary("0101");
58 max_odd_binary("1111");
59 
60 sub max_odd_binary($str) {
61     say "Input: \"$str\"";
62     my @digits = sort {$b <=> $a} split //, $str;
63     push @digits, shift @digits;
64     say "Output: " . join("", @digits) . "\"";
65 }