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 <iostream>
2#include <string>
3using namespace std;
4
5string maxOddBinaryNumber(const string &s) {
6 int ones = 0, zeros = 0;
7 for (char c : s) {
8 if (c == '1')
9 ones++;
10 else
11 zeros++;
12 }
13 string result(ones - 1, '1');
14 result.append(string(zeros, '0'));
15 result += '1';
16 return result;
17}
18
19int main() {
20 string s = "0101";
21 cout << maxOddBinaryNumber(s) << endl;
22 return 0;
23}
This solution uses string manipulation, counting the number of '1's and '0's. It constructs a new string with maximum leading '1's and a trailing '1' to ensure oddness.
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
Array methods in JavaScript are used for easy sorting and positioning. Reassigning elements post-sort aligns with the maximum odd criteria.