Leetcode 2864. Maximum Odd Binary Number
Given a binary string s
, you need to rearrange the characters of s
such that the resultant binary number is the largest possible odd binary number.
A binary number is odd if its last digit is 1
.
s
consisting only of '0'
and '1'
.s
.To form the largest possible binary number, you need to ensure the most significant bits are 1
s. However, to ensure the binary number is odd, its last digit must be 1
.
1
s and 0
s in the string.1
s in the highest order positions but preserve at least one 1
to ensure the number ends in 1
.0
s.1
s and 0
s.1
s first except for one 1
at the end.0
s.1
.Here is a C++ function to implement the strategy described:
#include <string>
#include <algorithm>
std::string maximumOddBinaryNumber(std::string s) {
int count1 = std::count(s.begin(), s.end(), '1');
int count0 = s.size() - count1;
std::string result(count1 - 1, '1'); // Place count1-1 1's first
result.append(count0, '0'); // Then append count0 0's
result.append(1, '1'); // Finally append the last 1
return result;
}
1
s and 0
s:
count1
: Total count of 1
s in the string.count0
: Total count of 0
s in the string (can be derived from total length - count1).count1 - 1
1
s to make the number as large as possible.0
s.1
to ensure the number is odd.O(n)
where n
is the length of the input string, as we traverse the string to count 1
s and 0
s once and construct the new string in linear time.This approach ensures we achieve the largest possible odd binary number by maximizing the number of leading 1
s and ensuring the last digit is 1
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?