力扣数字的补数链接
题解:
class Solution {
/**
* @param Integer $num
* @return Integer
*/
function findComplement($num) {
if($num==1){
return 0;
}
$binNum = $this->toBin($num);
$rev = $this->toRev($binNum);
$result = 0;
$len = strlen($rev);
for($j = $len -1 ; $j>=0;$j-- ){
if(substr($rev,$j,1)==1){
$result+= pow(2,$len-$j-1);
}
}
return $result;
}
private function toBin($nums){
if($nums==0 || $nums == 1){
return $nums;
}
$divisor = intval($nums/2);
$binNum = intval($nums%2);
return $binNum.$this->toBin($divisor);
}
private function toRev($binNum){
$rev='';
$binNum = strrev($binNum);
for($i = 0 ; $i<strlen($binNum);$i++){
if(substr($binNum,$i,1)==1){
$rev.='0';
}else{
$rev.='1';
}
}
return $rev;
}
}
网友评论