<?php
error_reporting(0);
//数组中其他数字出现二次,而x出现一次 求x
function demo1(){
$arr = array(1,2,3,2,1);
$n = 0;
for($i = 0; $i<count($arr);$i++)
$n ^= $arr[$i];
echo ($n);
}
//其他数字出现3次,x出现一次 求x
function 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.youkuaiyun.com/morewindows/article/details/12684497
http://www.cnblogs.com/aLittleBitCool/archive/2011/04/14/2015720.html