75 words
1 minute
力扣每日一题 20260225

1356. 根据数字二进制下 1 的数目排序#

没啥难度,按照题目要求写 cmp 函数,然后 sort 一下就行了。

代码:

class Solution {
public:
static bool cmp(int x, int y) {
if (popcount((size_t)x) != popcount((size_t)y))
return popcount((size_t)x) < popcount((size_t)y);
else
return x < y;
}
vector<int> sortByBits(vector<int>& arr) {
sort(arr.begin(), arr.end(), cmp);
return arr;
}
};
力扣每日一题 20260225
https://fuwari.vercel.app/posts/leetcode_daily/0225/
Author
P19E99
Published at
2026-02-25
License
CC BY-NC-SA 4.0