[LeetCode] Sort Integers by Binary Reflection

3769. Sort Integers by Binary Reflection

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
int rev(int x) {
int res = 0;
while(x) {
res = res * 2 + (x & 1);
x /= 2;
}
return res;
}
public:
vector<int> sortByReflection(vector<int>& nums) {
vector<pair<int,int>> S;
for(auto& n : nums) S.push_back({rev(n),n});
sort(begin(S), end(S));
vector<int> res;
for(auto& [a,b] : S) res.push_back(b);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/sort-integers-by-binary-reflection/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.