When given a binary string containing at least one '1', the task is to rearrange the bits to create the maximum odd binary number possible. To achieve this, it's essential to understand the optimal positioning of the '1's within the string to maximize the resulting value.
Understanding the Approach
The key to forming the greatest odd number lies in placing the '1's in a specific manner. By placing the rest of the '1's in front of the string and having the final '1' at the end, we can ensure that the resulting binary number is the maximum odd number possible.
Formulating the Result
The resulting string can be expressed as:
(total-1 '1's) + (total '0's) + '1'
By employing this strategy, it becomes possible to rearrange the given binary string to form the maximum odd binary number, optimizing the positioning of the '1's to achieve the desired result.
Code
class Solution {
public:
string maximumOddBinaryNumber(string s) {
int c1=0, c0=0;
for (auto a: s)
{
if(a=='1') c1++;
else c0++;
}
return (string(c1-1, '1') + string(c0,'0') + '1');
}
};
Top comments (0)