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 1s. However, to ensure the binary number is odd, its last digit must be 1.
1s and 0s in the string.1s in the highest order positions but preserve at least one 1 to ensure the number ends in 1.0s.1s and 0s.1s first except for one 1 at the end.0s.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;
}
1s and 0s:
count1: Total count of 1s in the string.count0: Total count of 0s in the string (can be derived from total length - count1).count1 - 1 1s to make the number as large as possible.0s.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 1s and 0s 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 1s 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?