只出现一次的数

来源:互联网 发布:照片真假辨别软件 编辑:程序博客网 时间:2024/05/02 04:28

<?phperror_reporting(0);//数组中其他数字出现二次,而x出现一次 求xfunction demo1(){  $arr = array(1,2,3,2,1);  $n = 0;  for($i = 0; $i<count($arr);$i++)  $n ^=  $arr[$i];  echo ($n);}//其他数字出现3次,x出现一次 求xfunction demo2()  {    $bits =array();  $arr = array(2, 3, 1, 2, 3, 4, 1, 2, 3, 1);   for($i = 0; $i<count($arr);$i++)      for ($j = 0; $j < 32; $j++)        $bits[$j] += ( ($arr[$i] >> $j) & 1);    // 如果某位上的结果不能被整除,则肯定目标数字在这一位上为     $result = 0;    for ($j = 0; $j < 32; $j++)      if ($bits[$j] % 3 != 0)        $result += (1 << $j);    echo $result;  } //找出数组中两个只出现一次的数字function demo3(){    $arr = array(1,2,3,4,5,6,4,3,2,1);    $ansXor=0;    for($i = 0; $i<count($arr);$i++)  {        $ansXor^=$arr[$i];               //异或    }    $pos=findFirstOne($ansXor);    $num1=$num2=0;    for($i = 0; $i<count($arr);$i++) {        if(testBit($arr[$i],$pos))            $num1^=$arr[$i];        else            $num2^=$arr[$i];    }    echo $num1.'  '.$num2  ;}function  findFirstOne($value){     //取二进制中首个为1的位置    $pos=1;    while(($value&1)!=1){        $value=$value>>1;        $pos++;    }    return $pos;}function  testBit($value,$pos){  //测试某位置是否为1    return (($value>>$pos)&1);}demo3();


http://blog.csdn.net/morewindows/article/details/12684497

http://www.cnblogs.com/aLittleBitCool/archive/2011/04/14/2015720.html

0 0
原创粉丝点击