Move History

Rooted by: BinaryGap
Fork Selected
  • Fundamentals
    Logic
    Code
    // > given a positive integer N
    // do not have to account for N of 0
    
    function binaryGap($n) 
    {
      return preg_match_all('/1(0+)1/', decbin($n), $matches) ? max(array_map('strlen', $matches[1])) : 0;
    }
    Test Cases
    <?php
    use PHPUnit\Framework\TestCase;
    
    // PHPUnit Test Examples:
    // TODO: Replace examples and use TDD by writing your own tests
    class ExampleTest extends TestCase
    {
        // test function names should start with "test"
        public function testThatSomethingShouldHappen() {
          $this->assertEquals(5, binaryGap(1041));
          $this->assertEquals(2, binaryGap(9));
          $this->assertEquals(0, binaryGap(15));
        }
    }
    
  • Code
    • // > given a positive integer N
    • // do not have to account for N of 0
    • function binaryGap($n)
    • {
    • while (!($n & 1))
    • {
    • $n >>= 1;
    • }
    • $n >>= 1;
    • $max = 0;
    • $current = 0;
    • while ($n)
    • {
    • if ($n & 1)
    • {
    • $max = max($max, $current);
    • $current = 0;
    • }
    • else
    • {
    • ++$current;
    • }
    • $n >>= 1;
    • }
    • return $max;
    • }
    • return preg_match_all('/1(0+)1/', decbin($n), $matches) ? max(array_map('strlen', $matches[1])) : 0;
    • }