目录
左移运算
左移运算,顾名思义就是对其二进制表示向左移动一位,低位补0。因为二进制的每一位在十进制中的意义,所以左移运算就相当于。对于溢出的问题,左移运算也会直接忽视这一问题,高位溢出就直接扔掉就可以了(自然溢出)。
190. 颠倒二进制位
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t ans=0;
for(int i=0;i<32;i++) {
ans=(ans<<1)|(n&1);
n>>=1;
}
return ans;
}
};
231. 2 的幂
class Solution {
public:
bool isPowerOfTwo(int n) {
for(int i=0;i<31;i++) {
if((1<<i)==n) return true;
}
return false;
}
};
476. 数字的补数
class Solution {
public:
int findComplement(int num) {
int ans=0,cnt=0;
while(num) {
int t=num&1;
if(!t) ans|=1<<cnt;
cnt++;
num>>=1;
}
return ans;
}
};
338. 比特位计数
class Solution {
public:
vector<int> countBits(int n) {
vector<int>res;
for(int i=0;i<=n;i++) {
int j=i,cnt=0;
while(j) {
if(j&1) cnt++;
j>>=1;
}
res.push_back(cnt);
}
return res;
}
};