[LeetCode] Maximum Odd Binary Number

2864. Maximum Odd Binary Number

You are given a binary string s that contains at least one '1'.

You have to rearrange the bits in such a way that the resulting binary number is the maximum odd binary number that can be created from this combination.

Return a string representing the maximum odd binary number that can be created from the given combination.

Note that the resulting string can have leading zeros.

1
2
3
4
5
6
7
8
9
10
11
12
13
14

class Solution {
public:
string maximumOddBinaryNumber(string s) {
sort(rbegin(s), rend(s));
for(int i = s.length() - 1; i >= 0; i--) {
if(s[i] == '0') continue;
s[i] = '0';
s.back() = '1';
break;
}
return s;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/09/24/PS/LeetCode/maximum-odd-binary-number/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.