在 LeetCode 上交的第二个题,应该说这道题考查的是C中的"位运算"一节,但是谁也想不出
按位异或(^)运算符会这样考,确实挺服气出题人的思维与智商,活不多说,直接看代码吧;
代码实现:
#include <iostream> #include <fstream> using namespace std; /* 解题思路: 在C/C++语言中,按位异或运算符^ 会对两端的值得二进制位 进行运算,只有当同一位的两个数不同时,它的值才会是1, 比如说: (1) 1 ^ 2 二进制为: 0000 0001 ^ 0000 0010 ____________ = 0000 0011 = 3(十进制) (2) 1 ^ 1 0000 0001 ^ 0000 0001 ___________ = 0000 0000 = 0(十进制) 所以两个相同的数异或的结果永远为0,而0 ^ a == a, 所以,将数组中所有元素都进行异或, 得到结果就是只出现一次的元素. */ class Solution { public: int singleNumber(int A[], int n) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if (n <= 0) return -1; int ans = 0; for (int i = 0; i < n; i++) ans ^= A[i]; return ans; } }; // 测试代码 int main() { int a[7]; //freopen("input.txt","r",stdin); Solution s; for(int i = 0; i < 7; i++) cin >> a[i]; cout << s.singleNumber(a,7) << endl; return 0; } //测试数据: //1 2 3 1 2 3 4