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.
1public class MaxOddBinaryNumber {
2 public static String maxOddBinary(String s) {
3 int ones = 0, zeros = 0;
4 for (char c : s.toCharArray()) {
5 if (c == '1')
6 ones++;
7 else
8 zeros++;
9 }
10 StringBuilder sb = new StringBuilder();
11 for (int i = 0; i < ones - 1; i++) sb.append('1');
12 for (int i = 0; i < zeros; i++) sb.append('0');
13 sb.append('1');
14 return sb.toString();
15 }
16
17 public static void main(String[] args) {
18 String s = "0101";
19 System.out.println(maxOddBinary(s));
20 }
21}
The code initializes counters for '1' and '0'. It constructs a StringBuilder by appending the appropriate number of each character, ensuring the last character is '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.
1
Solve with full IDE support and test cases
Java's Arrays.sort used here ensures proper arrangement; swapping ensures legality where '1' must end the string.