mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01:00
rs: add «2864. Maximum Odd Binary Number»
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
981c119d36
commit
8d4fc53789
1 changed files with 21 additions and 0 deletions
21
rs/maximum-odd-binary-number.rs
Normal file
21
rs/maximum-odd-binary-number.rs
Normal file
|
@ -0,0 +1,21 @@
|
|||
use std::cmp;
|
||||
|
||||
impl Solution {
|
||||
pub fn maximum_odd_binary_number(s: String) -> String {
|
||||
let mut bits: Vec<char> = s.chars().collect();
|
||||
|
||||
// sort in reverse order, all ones are at the beginning
|
||||
bits.sort_unstable_by_key(|&x| cmp::Reverse(x));
|
||||
|
||||
// find the last one
|
||||
let i = bits.iter().rposition(|&x| x == '1').unwrap();
|
||||
|
||||
// and swap with the last zero to obtain odd integer
|
||||
let last_index = bits.len() - 1;
|
||||
if i < last_index {
|
||||
bits.swap(i, last_index);
|
||||
}
|
||||
|
||||
bits.into_iter().collect()
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue