数据结构练习(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;
}

 

posted @ 2012-12-17 14:41  kedebug  阅读(177)  评论(0编辑  收藏  举报