Maximum Odd Binary Number

Maximum Odd Binary Number

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!

https://leetcode.com/problems/maximum-odd-binary-number/solutions/4804745/o-n-space-and-o-n-time

要查看或添加评论,请登录

Sajid Khan的更多文章

  • 141. Linked List Cycle

    141. Linked List Cycle

    Please refer to LeetCode for the question details: https://leetcode.com/problems/linked-list-cycle/description/ We are…

  • Minimum Length of String After Deleting Similar Ends

    Minimum Length of String After Deleting Similar Ends

    Please refer to LeetCode for the question details:…

  • Bag of Tokens

    Bag of Tokens

    Please refer to LeetCode for the question descriptions. https://leetcode.

  • Even Odd Tree

    Even Odd Tree

    https://leetcode.com/problems/even-odd-tree/description/?envType=daily-question&envId=2024-02-29 If you look into the…

    1 条评论

社区洞察

其他会员也浏览了