位操作(Bit Manipulation)是程序设计中对位模式或二进制数的一元和二元操作。在许多古老的微处理器上,位运算比加减运算略快,通常位运算比乘除法运算要快很多。在现代编程语言中,情况并非如此,很多编程语言的解释器都会基本的运算进行了优化,因此我们在实际开发中可以不必做一些编译器已经帮我们做好的优化,而就写出代码本身所要表现的意思。
位运算的问题,很多都很有技巧性,大家需要掌握一定的位运算的应用,达到融会贯通的目的。
0 and 0 = 0;0 and 1 = 0;
1 or 1 = 1;1 or 0 = 1;
1. 二进制求和
class Solution {
public:
string addBinary(string a, string b) {
int m = a.length();
int n = b.length();
string ans="";
int i=m-1;
int j=n-1;
int c=0;
while(i>=0 && j>=0){
if((a[i]-'0')+(b[j]-'0') + c ==0){
c = 0;
ans = '0'+ans;
i--;
j--;
}else if((a[i]-'0')+(b[j]-'0') + c ==1){
c = 0;
ans = '1'+ans;
i--;
j--;
}else if((a[i]-'0')+(b[j]-'0') + c ==2){
c = 1;
ans = '0'+ans;
i--;
j--;
}else if((a[i]-'0')+(b[j]-'0') + c ==3){
c = 1;
ans = '1'+ans;
i--;
j--;
}
}
if(i>=0){
for(int k=i;k>=0;k--){
if((a[k]-'0') + c ==0){
c = 0;
ans = '0'+ans;
}else if((a[k]-'0') + c ==1){
c = 0;
ans = '1'+ans;
}else if((a[k]-'0') + c ==2){
c = 1;
ans = '0'+ans;
}
}
}
if(j>=0){
for(int k=j;k>=0;k--){
if((b[k]-'0') + c ==0){
c = 0;
ans = '0'+ans;
}else if((b[k]-'0') + c ==1){
c = 0;
ans = '1'+ans;
}else if((b[k]-'0') + c ==2){
c = 1;
ans = '0'+ans;
}
}
}
if(c==1){
ans = '1'+ans;
}
return ans;
}
};
for循环里面若不满足条件了便不会再递改变量;
注意字符数字与数字之间的转换。
2. 位1的个数
class Solution {
public:
int hammingWeight(uint32_t n) {
int ans=0;
while(n)
{
ans=ans+n%2;
n=n>>1;
}
return ans;
}
};