两位1之间的最大间隙,二进制当量十进制数

时间:2014-06-18 12:56:25

标签: php algorithm

我想编写一个程序,以二进制等值的十进制数找到两个1之间的最大间隙。例如,对于100101:间隙为2,对于10101:间隙为1.

<?php
$numberGiven = 251;
$binaryForm = decbin($numberGiven);

$status = false;
$count = 0;
for($i = 0; $i < strlen($binaryForm); $i++)
{
    var_dump($binaryForm[$i]);
    if($binaryForm[$i] == 1)
    {
        $status = false;
        $count = 0;
    }
    else
    {
        $status = true;
        $count += 1;
    }
}
echo "count = " . $count . "<br>";
echo $binaryForm;
?>

但我没有成功..

3 个答案:

答案 0 :(得分:3)

您目前正在做的是每次找到1时重置计数。

您需要跟踪当前的最大值:

$count = 0;
$maxCount = 0;

以及您设置$count = 0的位置,您还应该

if ($count > $maxCount)
  $maxCount = $count;
$count = 0;

然后

echo "count = " . $maxCount . "<br>";

总之:

<?php
$numberGiven = 251;
$binaryForm = decbin($numberGiven);

$status = false;    
$count = 0;
$maxCount = 0;

for($i = 0; $i < strlen($binaryForm); $i++)
{
  // Don't count leading zeroes.
  if ($status == false && $binaryForm[$i] == 0) continue;
  $status = true;

  var_dump($binaryForm[$i]);

  // We've found a 1. Remember the count.
  if($binaryForm[$i] == 1)
  {
    if ($count > $maxCount)
      $maxCount = $count;
    $count = 0;
  }
  // We found a 0. Add one to count.
  else
  {
    $count += 1;
  }
}

echo "count = " . $count . "<br>";
echo $binaryForm;
?>

免责声明: 未经过测试的代码

答案 1 :(得分:3)

我会使用binary right-shift operator >>并迭代地移位1位,并检查当前最右边的位是1,直到我检查了所有位。如果找到1,则会计算之前1之间的差距:

foreach(array(5,17,25,1223243) as $number) {
    $lastpos = -1; 
    $gap = -1; // means there are zero or excatly one '1's

    // PHP_INT_SIZE contains the number of bytes an integer
    // will consume on your system. The value * 8 is the number of bits.
    for($pos=0; $pos < PHP_INT_SIZE * 8; $pos++) {
        if(($number >> $pos) & 1) {
            if($lastpos !== -1) {
                $gap = max($gap, $pos - $lastpos -1);
            }
            $lastpos = $pos;
        }
    }   

    echo "$number " . decbin($number) . "  ";
    echo "max gap: {$gap}\n";
}

输出:

5 101  max gap: 1
17 10001  max gap: 3
25 11001  max gap: 2
1223243 100101010101001001011  max gap: 2

答案 2 :(得分:3)

使用正则表达式查找&#34; 0&#34;组,按长度降序排序,取第一个,得到长度:

$numberGiven = 251;
$binaryForm = decbin($numberGiven);

preg_match_all('/(0+)/', $binaryForm, $matches);
$matches = $matches[0];

rsort($matches, SORT_STRING);
echo 'count = ' . strlen($matches[0]) . '<br>';
echo $binaryForm;

更新:基于Mark Ba​​ker的评论。

更新#2:由afeijo在下面的评论中提出,上述内容并不排除结尾零。以下是解决方案:

preg_match_all('/(0+)1/', $binaryForm, $matches);
$matches = $matches[1];