aboutsummaryrefslogtreecommitdiff
path: root/max_odd_binary_num.c
diff options
context:
space:
mode:
authorjack <[email protected]>2024-06-14 13:13:15 -0600
committerjack <[email protected]>2024-06-14 13:13:15 -0600
commitd343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch)
tree96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /max_odd_binary_num.c
downloadleetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz
leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip
initial
Diffstat (limited to 'max_odd_binary_num.c')
-rw-r--r--max_odd_binary_num.c32
1 files changed, 32 insertions, 0 deletions
diff --git a/max_odd_binary_num.c b/max_odd_binary_num.c
new file mode 100644
index 0000000..86f6af1
--- /dev/null
+++ b/max_odd_binary_num.c
@@ -0,0 +1,32 @@
+// 2864. Maximum Odd Binary Number
+#include "leetcode.h"
+
+/*
+ * 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.
+ */
+
+char *maximumOddBinaryNumber(char *s) {
+ int n = strlen(s), one = 0;
+ for (int i = 0; i < n; ++i)
+ if (s[i] == '1')
+ one++;
+ for (int i = 0; i < n - 1; ++i) {
+ if (one > 1) {
+ s[i] = '1';
+ --one;
+ } else
+ s[i] = '0';
+ }
+ s[n - 1] = '1';
+ return s;
+}
+
+int main() {
+ char *s1 = "010", *s2 = "0101";
+ printf("%s\n", maximumOddBinaryNumber(s1)); // expect: 001
+ printf("%s\n", maximumOddBinaryNumber(s2)); // expect: 1001
+}