The Weekly Challenge 384

Base N and Special Binary Substrings

Task 1: Base N

Convert a given non-negative integer into base N representation (2 <= N <= 36).

Example Output

Input: $num = 255, $base = 16 Output: "FF" Input: $num = 35, $base = 36 Output: "Z"

Logic

Repeatedly extract remainders modulo base N and divide by N, mapping digit values 0-35 to characters '0'-'9' and 'A'-'Z'. Reverse the digit sequence to produce the result.

Perl Solution

ch-1.pl

sub convert_base ( $num, $base ) { return '0' if $num == 0; my @digits = ( '0' .. '9', 'A' .. 'Z' ); my $result = ''; while ( $num > 0 ) { my $rem = $num % $base; $result = $digits[$rem] . $result; $num = int( $num / $base ); } return $result; }

Python Solution

ch-1.py

def convert_base(num: int, base: int) -> str: """Convert a non-negative integer into base N representation.""" if num == 0: return "0" digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" res: list[str] = [] while num > 0: num, rem = divmod(num, base) res.append(digits[rem]) return "".join(reversed(res))

Task 2: Special Binary Substrings

A special binary string has equal count of 0s and 1s, and every prefix has at least as many 1s as 0s. Return the lexicographically largest special binary string by swapping contiguous special substrings.

Example Output

Input: $binary = "11011000" Output: "11100100"

Logic

Decompose the string into primitive special blocks '1' + inner + '0'. Recursively maximize each inner component and sort top-level blocks in descending order.

Perl Solution

ch-2.pl

sub special_binary_substrings ($binary) { return '' if length($binary) == 0; my @chunks; my $count = 0; my $start = 0; for my $i ( 0 .. length($binary) - 1 ) { my $char = substr( $binary, $i, 1 ); $count += ( $char eq '1' ) ? 1 : -1; if ( $count == 0 ) { my $inner = substr( $binary, $start + 1, $i - $start - 1 ); push @chunks, '1' . special_binary_substrings($inner) . '0'; $start = $i + 1; } } @chunks = sort { $b cmp $a } @chunks; return join( '', @chunks ); }

Python Solution

ch-2.py

def special_binary_substrings(binary: str) -> str: """Return lexicographically largest special binary string.""" if not binary: return "" chunks: list[str] = [] count = 0 start = 0 for i, ch in enumerate(binary): count += 1 if ch == "1" else -1 if count == 0: inner = binary[start + 1 : i] chunks.append("1" + special_binary_substrings(inner) + "0") start = i + 1 chunks.sort(reverse=True) return "".join(chunks)