Sponsored
Sponsored
To form the maximum odd binary number from a given binary string, observe that the binary number should have '1' at the end to be odd. Among the remaining bits, arrange as many '1's as possible at the leading positions while maintaining the '1' at the end. This approach involves counting the occurrences of '1' and '0', then constructing the number.
Time Complexity: O(n), where n is the length of the string as it needs one pass to count and another to construct.
Space Complexity: O(1) for the counting variables.
1#include <stdio.h>
2#include <string.h>
3
4void maxOddBinaryNumber(char *s) {
5 int ones = 0, zeros = 0;
6 for (int i = 0; s[i] != '\0'; i++) {
7 if (s[i] == '1')
8 ones++;
9 else
10 zeros++;
11 }
12 ones--; // Reserve one '1' for the last position
13 while (ones-- > 0)
14 putchar('1');
15 while (zeros-- > 0)
16 putchar('0');
17 putchar('1'); // The last one
18 putchar('\n');
19}
20
21int main() {
22 char s[] = "0101";
23 maxOddBinaryNumber(s);
24 return 0;
25}
The program first counts the '1's and '0's. It reserves one '1' for the end to make the number odd. The rest of the '1's are placed at the beginning, and '0's fill the remaining positions before the final '1'.
A different approach involves sorting the binary string while ensuring a '1' is at the end. To maximize the binary number, the initial part of the string should consist of leading '1's followed by '0's, then append a single '1' at the end to turn the number odd.
Time Complexity: O(n log n) for sorting.
Space Complexity: O(1) assuming sorting in place is allowed.
1using System.Linq;
class MaxOddBinaryNumber
{
public static string MaxOddBinary(string s)
{
var arr = s.OrderByDescending(c => c).ToArray();
int lastOneIdx = Array.LastIndexOf(arr, '1');
char temp = arr[lastOneIdx];
arr[lastOneIdx] = arr[arr.Length - 1];
arr[arr.Length - 1] = temp;
return new string(arr);
}
static void Main()
{
string s = "0101";
Console.WriteLine(MaxOddBinary(s));
}
}
Solve with full IDE support and test cases
C# utilizes LINQ for sorting, and swapping readjusts the final string format to line up appropriately with binary considerations.