// we explode string by character '1' $exploded = explode('1', $binary); // binary gap must be surrounded by ones at both ends, // so there shouldn't be zeroes after last character '1' occurrence, and before first character '1' occurrence unset($exploded[count($exploded) - 1]); unset($exploded[0]); // we are searching for longest zeroes pattern foreach ($exploded as $zeroes) { $length = strlen($zeroes); if ($length > $binaryGap) { $binaryGap = $length; } } } $N = 1041; echo solution1($N); function solution1($N) { $binarygap = 0; $binary = decbin($N); $exploded = explode('1', $binary); return $exploded; } function solution1($N) { $binarygap = 0; $binary = decbin($N); $explode = explode("1", $binary); unset($explode[count($explode) - 1]); unset($explode[0]); foreach ($explode as $key => $value) {
{ // shifted array $shifted = array(); // number of elements $N = count($A); // if $K is bigger than $N, on $N-th shift we would be on starting position, // so it makes sense only to do smaller number of shifts than $N size $shiftedPositions = $K % $N; // initially first element position is 0, but at the end it will be K for ($i = 0; $i < $N; $i++) { $position = $i + $shiftedPositions; if ($position > $N - 1) { $position = $position - $N; } $shifted[$position] = $A[$i]; } ksort($shifted); return $shifted; } $A = [10, 2, 5, 1, 8, 20, 21]; $K = 3; echo solution1($A, $K); function solution1($A, $K) { $count = count($A); $newk = $K % $count; $right = array_slice($A, 0, $count - $newk); $left = array_slice($A, $count - $newk, $newk); $new = array_merge($left, $right); print_r($new); }