剑指offer 66题 -- 数组中只出现一次的数字

class Solution {
public:
void FindNumsAppearOnce(vector<int> str,int* num1,int *num2) {
  int exclusiveOr =0;

  for(int i=0; i< str.size(); ++i)
  {
    exclusiveOr ^= str[i];
  }
  
  unsigned int indexOf1 = getFirstBitOne( exclusiveOr );

  for(int i=0; i<str.size(); ++i)
  {
    if( isBit1(str[i], indexOf1) )
      *num1 ^= str[i];
    else
      *num2 ^= str[i];
  }

  return;
  }

  unsigned int getFirstBitOne( int num)
  {
    unsigned int indexBit=0;
    while( 0 ==(num&1) && indexBit <= 8*sizeof(int))
    {
      ++indexBit;
      num = num>>1;
    }

    return indexBit;
  }

 

  bool isBit1(int num, int bit)
  {
    num = num >> bit;
    return (num&1);
  }

};

posted @ 2017-03-09 20:32  夜雨寒山  阅读(84)  评论(0编辑  收藏  举报