Sum vs XOR
HackerRank 问题: Sum vs XOR
Categories:
Question
Given an integer n
, find each x
such that:
- 0 <= x <= n
- n + x = n ^ x
where ^ denotes the bitwise XOR operator. Return the number of x's
satisfying the criteria.
Answer
<?php
/*
* Complete the 'sumXor' function below.
*
* The function is expected to return a LONG_INTEGER.
* The function accepts LONG_INTEGER n as parameter.
*/
function sumXor($number) {
$sum_xor_number = 1;
if ($number == 0) {
return 1;
}
// transform number to binary number
$binary_number = decbin($number);
$binary_number_array = str_split($binary_number);
// search each binary number
foreach ($binary_number_array as $binary_code) {
if ($binary_code == 0) {
// when binary code is 0, then could be the sum xor number
$sum_xor_number*=2;
}
}
return $sum_xor_number;
}
$fptr = fopen(getenv("OUTPUT_PATH"), "w");
$n = intval(trim(fgets(STDIN)));
$result = sumXor($n);
fwrite($fptr, $result . "\n");
fclose($fptr);