欢迎大家积极在评论区留言发表自己的看法,知无不言,言无不尽,养成每天刷题的习惯,也可以自己发布优质的解题报告,供社区一同鉴赏,吸引一波自己的核心粉丝。
今天是新的开始 位运算 🔥


// 190. 颠倒二进制位
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t res = 0;
for(int i = 0; i < 32; ++i) {
res = (res << 1) | (n & 1);
n >>= 1;
}
return res;
}
};
// 338. 比特位计数
class Solution {
int cntBit(int n ) {
int cnt = 0;
while (n > 0)
{
if(n & 1)
cnt++;
n >>= 1;
}
return cnt;
}
public:
vector<int> countBits(int n) {
vector<int> ans;
for(int i = 0; i <= n; ++i) {
int cnt = cntBit(i);
ans.emplace_back(cnt);
}
return ans;
}
};
// 1356. 根据数字二进制下 1 的数目排序
class Solution {
static int cntBit(int n) {
int cnt = 0;
while (n > 0)
{
if(n & 1)
cnt++;
n >>= 1;
}
return cnt;
}
static bool cmp(int a, int b) {
int bitA = cntBit(a);
int bitB = cntBit(b);
if (bitA == bitB) return a < b; // 如果bit中1数量相同,比较数值大小
return bitA < bitB; // 否则比较bit中1数量大小
}
public:
vector<int> sortByBits(vector<int>& arr) {
sort(arr.begin(), arr.end(), cmp);
return arr;
}
};
// 1356. 根据数字二进制下 1 的数目排序(优化)
class Solution {
static int cntBit(int n) {
int cnt = 0;
while (n > 0)
{
n &= (n -1); // 这样写速度更快
cnt++;
}
return cnt;
}
static bool cmp(int a, int b) {
int bitA = cntBit(a);
int bitB = cntBit(b);
if (bitA == bitB) return a < b; // 如果bit中1数量相同,比较数值大小
return bitA < bitB; // 否则比较bit中1数量大小
}
public:
vector<int> sortByBits(vector<int>& arr) {
sort(arr.begin(), arr.end(), cmp);
return arr;
}
};
对比图:
