Skip to content

Instantly share code, notes, and snippets.

@lbvf50mobile
Last active August 6, 2020 15:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lbvf50mobile/bd564233de81e7c011393acbe6b7a4cc to your computer and use it in GitHub Desktop.
Save lbvf50mobile/bd564233de81e7c011393acbe6b7a4cc to your computer and use it in GitHub Desktop.
Just PHP FUN 069.
<?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;
}
@lbvf50mobile
Copy link
Author

function nextHigher($n) {
  echo "$n \n";
  $n = decbin($n);
  echo "$n - input\n";
  for($i = strlen($n) - 1, $j = strlen($n) - 2; $j > 0; $i -=1, $j-=1)
    if('0' == $n[$j] && '1' == $n[$i]){
      $n[$j] = '1'; $n[$i] = '0';
      echo "$n - output \n";
      return bindec($n);
    }
  
   $ones = substr_count($n,'1'); $zeros = substr_count($n,'0');
  return bindec("1".str_repeat('0',$zeros+1).str_repeat('1',$ones-1));
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment