# LeetCode解题中位运算的运用

 按位与 a&b 按位或 a|b 按位异或 a^b 按位取反 ~a 左移 a<>b

（1）136. Single Number（https://leetcode.com/problems/single-number/description/）

class Solution {
public:
int singleNumber(vector<int>& nums) {
int res = 0;
for (int i = 0; i < nums.size(); i++) {
res ^= nums[i];
}
return res;
}
};

（2）268. Missing Number（https://leetcode.com/problems/missing-number/description/）

class Solution {
public:
int missingNumber(vector<int>& nums) {
int sum = 0;
for (int i = 0; i < nums.size(); i++)  {
sum += nums[i];
}
int actual_sum = nums.size() * (nums.size() + 1) /2;
return actual_sum - sum;
}
};

class Solution {
public:
int missingNumber(vector<int>& nums) {
int res = 0;
int temp = 1;
for (int i = 0; i < nums.size(); i++) {
res ^= nums[i] ^ temp;
temp++;
}
return res;
}
};

（3）191. Number of 1 Bits（https://leetcode.com/problems/number-of-1-bits/description/）

class Solution {
public:
int hammingWeight(uint32_t n) {
int res = 0;
while (n) {
res += (n & 1);
n = n >> 1;
}
return res;
}
};

（4）求一个数是否2的幂

http://www.cnblogs.com/fengziwei/p/7570885.html

（5）371. Sum of Two Integers（https://leetcode.com/problems/sum-of-two-integers/description/）

class Solution {
public:
int getSum(int a, int b) {
int res = a ^ b;
int temp = (a & b) << 1;
while (temp) {
cout << res << endl;
cout << temp << endl;
int copy = res;
res = res ^ temp;
temp = (copy & temp) << 1;
}
return res;
}
};

（6）461. Hamming Distance（https://leetcode.com/problems/hamming-distance/description/）

class Solution {
public:
int hammingDistance(int x, int y) {
int temp = x ^ y;
int res = 0;
while (temp) {
res += temp & 1;
temp >>= 1;
}
return res;
}
};

posted @ 2017-09-24 19:48  fengzw  阅读(1598)  评论(0编辑  收藏  举报