Skip to content

Commit 6203693

Browse files
committed
Convert them into binary, sort them first by their summed bits and incase they are same, sort by the number for ascending order
1 parent 1c20694 commit 6203693

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

1356/main.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
impl Solution {
2+
pub fn sort_by_bits(arr: Vec<i32>) -> Vec<i32> {
3+
let mut output = arr
4+
.iter()
5+
.map(|&x| {
6+
let formatted_string = format!("{:b}", x)
7+
.chars()
8+
.map(|y| y.to_digit(10).unwrap())
9+
.sum::<u32>();
10+
(x, formatted_string)
11+
})
12+
.collect::<Vec<_>>();
13+
output.sort_by(|(c, a), (d, b)| if a != b { a.cmp(b) } else { c.cmp(d) });
14+
output.iter().map(|&(x, _)| x).collect()
15+
}
16+
}

0 commit comments

Comments
 (0)