前言
欢迎大家积极在评论区留言发表自己的看法,知无不言,言无不尽,养成每天刷题的习惯,也可以自己发布优质的解题报告,供社区一同鉴赏,吸引一波自己的核心粉丝。
今天是新的开始 位运算 🔥
一、练习题目
二、算法思路
- 1、190. 颠倒二进制位:🔥利用循环移位来做,思路比较简单好想。先看一个8位数的,思路就是n的末尾数字拼接到res中,直到n为0,就能实现颠倒。
- 2、338. 比特位计数:🔥简单题。
- 3、1356. 根据数字二进制下 1 的数目排序:🔥沿用了第二题的函数。
三、源码剖析
// 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;
}
};
- 1.每次把 res 左移,把 n 的二进制末尾数字拼接到结果 res 的末尾,然后把 n 右移。
// 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;
}
};
- 1.写一个统计1的个数函数,遍历去找即可。
// 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;
}
};
对比图: