数据结构练习(25)数组中只出现一次的数字
http://zhedahht.blog.163.com/blog/static/2541117420071128950682/
思路:
题目中处理last bit为1的时候不够优美。实际上 lastbit = x & (-x).
#include <iostream> void findNumber(int data[], int length, int &num1, int &num2) { if (length < 2) return ; int xor = 0; for (int i = 0; i < length; ++i) xor ^= data[i]; int lastbit = xor & (-xor); num1 = num2 = 0; for (int i = 0; i < length; ++i) { if (data[i] & lastbit) num1 ^= data[i]; else num2 ^= data[i]; } } int main() { int data[10] = {1, 2, 3, 3, 4, 4, 5, 5}; int num1, num2; findNumber(data, 8, num1, num2); return 0; }
-------------------------------------------------------
kedebug
Department of Computer Science and Engineering,
Shanghai Jiao Tong University
E-mail: kedebug0@gmail.com
GitHub: http://github.com/kedebug
-------------------------------------------------------