#3769
Easy Algorithms Sort integers by binary reflection
Array Sorting
60.7% acceptance
Feb 25, 2026
53
5
You are given an integer array nums.
The binary reflection of a positive integer is defined as the number obtained by reversing the order of its binary digits (ignoring any leading zeros) and interpreting the resulting binary number as a decimal.
Sort the array in ascending order based on the binary reflection of each element. If two different numbers have the same binary reflection, the smaller original number should appear first.
Return the resulting sorted array.
Solution
Rust
Time O(n log n)
Space O(n)
impl Solution {
pub fn sort_by_reflection(nums: Vec<i32>) -> Vec<i32> {
fn reflect(n: i32) -> i32 {
let bits = format!("{:b}", n);
let rev: String = bits.chars().rev().collect();
i32::from_str_radix(&rev, 2).unwrap()
}
let mut v: Vec<(i32, i32)> = nums.iter().map(|&n| (reflect(n), n)).collect();
v.sort();
v.iter().map(|&(_, n)| n).collect()
}
}