找出出现奇数次的元素
#include<iostream> using namespace std; bool question1(const int a[],const int n, int &num) { int temp = 0; for(int i = 0;i< n;i++) temp ^= a[i]; num = temp; return true; } bool question2(const int a[],const int n, int &num1,int &num2) { unsigned int temp = 0; for(int i = 0;i< n;i++) temp ^= a[i]; int k = 0; while(temp&1 == 0) { temp = temp>>1; k++; } num1 = 0; num2 = 0; for(int i = 0;i< n;i++) { if(((a[i]>>k)&1) == 0) ///注意这里的执行顺序 num1 ^= a[i]; else num2 ^= a[i]; } return true; } int main() { int a1[] = {1,1,2,2,3,3,4}; int a2[] = {1,1,2,3,4,4}; int r1,r2,r3; question1(a1,7,r1); question2(a2,6,r2,r3); cout<<r1<<" "<<r2<<" "<<r3; }
berkeleysong
posted on 2014-05-18 21:24 berkeleysong 阅读(209) 评论(0) 编辑 收藏 举报