Maximum Odd Binary Number
Sajid Khan
Senior Front-End Engineer | Web Developer | JavaScript ES6 | TypeScript | ReactJs | NextJs | NodeJs | MongoDB
Of course, the month begins with a simple question, but it's important to attempt every challenge.
In this question, we are given a binary string and tasked with rearranging it to form the largest possible odd number.
There are several solutions to this straightforward problem, and I'll share one of them.
The solution is straightforward. In every odd binary number, there is a '1' in the least significant place, meaning every odd binary number ends in '1'.
To find the largest odd number, we count the total number of '1's in the binary string using a loop. Then, we construct a new array by adding (totalOnes - 1) '1's at the beginning, (string.length - totalOnes) '0's after that, and finally a '1' at the end. This new array represents the largest odd number possible from the given binary string. Simply convert this array to a string and return it. That's all there is to it!
Here is the final code:
function maximumOddBinaryNumber(s: string): string {
let ones = 0;
for (let i = 0; i < s.length; i++) {
if (s[i] === '1') ones++
}
return `${'1'.repeat(ones - 1)}${'0'.repeat(s.length - ones)}1`;
};
Please consider upvoting my solution if you found it helpful!