From cc36203e4378c7ae217a35549f33539a46bc4449 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Wed, 13 Mar 2024 10:08:32 +0800 Subject: [PATCH] 20240313 Finished --- src/problem/mod.rs | 3 +- .../p2864_maximum_odd_binary_number.rs | 52 +++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 src/problem/p2864_maximum_odd_binary_number.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 60dd272..5eb218c 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -71,4 +71,5 @@ mod p2834_find_the_minimum_possible_sum_of_a_beautiful_array; mod p2386_find_the_k_sum_of_an_array; mod p299_bulls_and_cows; mod p2129_capitalize_the_title; -mod p1261_find_elements_in_a_contaminated_binary_tree; \ No newline at end of file +mod p1261_find_elements_in_a_contaminated_binary_tree; +mod p2864_maximum_odd_binary_number; \ No newline at end of file diff --git a/src/problem/p2864_maximum_odd_binary_number.rs b/src/problem/p2864_maximum_odd_binary_number.rs new file mode 100644 index 0000000..249e953 --- /dev/null +++ b/src/problem/p2864_maximum_odd_binary_number.rs @@ -0,0 +1,52 @@ +/** + * [2864] Maximum Odd Binary Number + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn maximum_odd_binary_number(s: String) -> String { + let nums: Vec = s.chars() + .map(|c| c.to_digit(10).unwrap()) + .collect(); + + let mut one_count = 0; + let mut zero_count = 0; + + for num in &nums { + if *num == 1 { + one_count += 1; + } else if *num == 0 { + zero_count += 1; + } + } + + let mut result: Vec = Vec::with_capacity(nums.len()); + + for _ in 1..one_count { + result.push('1'); + } + + for _ in 0..zero_count { + result.push('0'); + } + + result.push('1'); + result.iter().collect() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2864() { + assert_eq!("001", Solution::maximum_odd_binary_number("010".to_owned())); + assert_eq!("1001", Solution::maximum_odd_binary_number("0101".to_owned())); + } +}