LeetCode 2864: Maximum Odd Binary Number Solution
Master LeetCode problem 2864 (Maximum Odd Binary Number), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation
To find the maximum odd binary number, we need to place all the '1's at the end of the string and the '0's before them. The order of the '0's does not matter as long as they are before the '1's.
- Iterate through the input binary string and count the number of '1's.
- Create a new string with the remaining length after removing the '1's from the original string and fill it with '0's.
- Append the '1's at the end of the new string to get the maximum odd binary number.
Time Complexity: O(n) where n is the length of the input string. Space Complexity: O(n) where n is the length of the input string.
Solution Code
class Solution {
public String maximumOddBinaryNumber(String s) {
int onesCount = 0;
StringBuilder result = new StringBuilder();
for (char c : s.toCharArray()) {
if (c == '1') {
onesCount++;
} else {
result.append('0');
}
}
result.append("1".repeat(onesCount));
return result.toString();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2864 (Maximum Odd Binary Number)?
This page provides optimized solutions for LeetCode problem 2864 (Maximum Odd Binary Number) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2864 (Maximum Odd Binary Number)?
The time complexity for LeetCode 2864 (Maximum Odd Binary Number) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2864 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2864 in Java, C++, or Python.