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.
1def max_odd_binary_number(s):
2 ones = s.count('1')
3 zeros = s.count('0')
4 return '1' * (ones - 1) + '0' * zeros + '1'
5
6s = "0101"
7print(max_odd_binary_number(s))
Python's use of string counting methods allows a compact solution. The function transforms counted values into the maximum binary string configuration.
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#include <algorithm>
#include <string>
using namespace std;
string maxOddBinaryNumber(string s) {
sort(s.rbegin(), s.rend());
auto last_one_pos = s.find_last_of('1');
s.push_back(s[last_one_pos]);
s.erase(last_one_pos, 1);
return s;
}
int main() {
string s = "0101";
cout << maxOddBinaryNumber(s) << endl;
return 0;
}
Solve with full IDE support and test cases
Using C++'s sort function directly manipulates the string. After sorting, manipulating positions ensures a '1' at the end.