Skip to content

Commit 6f81fe3

Browse files
committed
Sync LeetCode submission Runtime - 47 ms (9.05%), Memory - 16.5 MB (31.46%)
1 parent e6f94e3 commit 6f81fe3

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<p>You are given a <strong>binary</strong> string <code>s</code> that contains at least one <code>&#39;1&#39;</code>.</p>
2+
3+
<p>You have to <strong>rearrange</strong> the bits in such a way that the resulting binary number is the <strong>maximum odd binary number</strong> that can be created from this combination.</p>
4+
5+
<p>Return <em>a string representing the maximum odd binary number that can be created from the given combination.</em></p>
6+
7+
<p><strong>Note </strong>that the resulting string <strong>can</strong> have leading zeros.</p>
8+
9+
<p>&nbsp;</p>
10+
<p><strong class="example">Example 1:</strong></p>
11+
12+
<pre>
13+
<strong>Input:</strong> s = &quot;010&quot;
14+
<strong>Output:</strong> &quot;001&quot;
15+
<strong>Explanation:</strong> Because there is just one &#39;1&#39;, it must be in the last position. So the answer is &quot;001&quot;.
16+
</pre>
17+
18+
<p><strong class="example">Example 2:</strong></p>
19+
20+
<pre>
21+
<strong>Input:</strong> s = &quot;0101&quot;
22+
<strong>Output:</strong> &quot;1001&quot;
23+
<strong>Explanation: </strong>One of the &#39;1&#39;s must be in the last position. The maximum number that can be made with the remaining digits is &quot;100&quot;. So the answer is &quot;1001&quot;.
24+
</pre>
25+
26+
<p>&nbsp;</p>
27+
<p><strong>Constraints:</strong></p>
28+
29+
<ul>
30+
<li><code>1 &lt;= s.length &lt;= 100</code></li>
31+
<li><code>s</code> consists only of <code>&#39;0&#39;</code> and <code>&#39;1&#39;</code>.</li>
32+
<li><code>s</code> contains at least one <code>&#39;1&#39;</code>.</li>
33+
</ul>
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# Approach 2: Greedy Bit Manipulation (Counting Ones)
2+
# Time: O(n)
3+
# Space: O(n)
4+
5+
class Solution:
6+
def maximumOddBinaryNumber(self, s: str) -> str:
7+
n = len(s)
8+
ones_cnt = s.count('1')
9+
10+
return '1' * (ones_cnt - 1) + '0' * (n - ones_cnt) + '1'
11+

0 commit comments

Comments
 (0)