面试题 05.01. 插入¶
class Solution {
public:
int insertBits(int N, int M, int i, int j) {
for (int k = i; k <= j; k++) {
//这里用longlong是为了防止出现越界
//与0相与将i到j的二进制全部变成0
N &= ~((long long) 1 << k);
}
return N | (M << i);
}
};
面试题 16.01. 交换数字¶
本题使用了位运算的性质:
- a^a=0
- a^0=a
因此本题解析为:
a=a^b;
b=a^b=(a^b)^b=a^(b^b)=a^0=a
a=a^b=a^b^a=0^b=b
class Solution {
public:
vector<int> swapNumbers(vector<int> &numbers) {
numbers[0] = numbers[0] ^ numbers[1];
numbers[1] = numbers[0] ^ numbers[1];
numbers[0] = numbers[0] ^ numbers[1];
return numbers;
}
};