- https://www.codewars.com/kata/56bdd0aec5dc03d7780010a5 Basics 08: Find next higher number with same Bits (1's).
Started at 21:33 06.08.2020 Thursday Aug.
Finished at 22:46 06.08.2020 Thursday Aug. (1hr 13minutes)
Started at 21:33 06.08.2020 Thursday Aug.
Finished at 22:46 06.08.2020 Thursday Aug. (1hr 13minutes)
<?php | |
# https://www.geeksforgeeks.org/next-higher-number-with-same-number-of-set-bits/ | |
# https://www.codewars.com/kata/56bdd0aec5dc03d7780010a5 Basics 08: Find next higher number with same Bits (1's). | |
function nextHigher($x) { | |
$next = 0; | |
if($x) | |
{ | |
// right most set bit | |
$rightOne = $x & - $x; | |
// reset the pattern and set next higher | |
// bit left part of x will be here | |
$nextHigherOneBit = $x + $rightOne; | |
// nextHigherOneBit is now part [D] of | |
// the above explanation. | |
// isolate the pattern | |
$rightOnesPattern = $x ^ $nextHigherOneBit; | |
// right adjust pattern | |
$rightOnesPattern = intval(($rightOnesPattern) / | |
$rightOne); | |
// correction factor | |
$rightOnesPattern >>= 2; | |
// rightOnesPattern is now part [A] | |
// of the above explanation. | |
// integrate new pattern (Add [D] and [A]) | |
$next = $nextHigherOneBit | $rightOnesPattern; | |
} | |
return $next; | |
} |