Programa PHP para contagem de bits definidos em um inteiro
Escreva um programa eficiente para contar o número de 1s na representação binária de um inteiro.
Exemplos :
Input : n = 6 Output : 2 Binary representation of 6 is 110 and has 2 set bits Input : n = 13 Output : 3 Binary representation of 11 is 1101 and has 3 set bits
<?php
// Function to get no of set
// bits in binary representation
// of positive integer n
function countSetBits($n)
{
$count = 0;
while ($n)
{
$count += $n & 1;
$n >>= 1;
}
return $count;
}
// Driver Code
$i = 9;
echo countSetBits($i);
// This code is contributed by ajit
?>
<?php
// PHP implementation of recursive
// approach to find the number of
// set bits in binary representation
// of positive integer n
// recursive function
// to count set bits
function countSetBits($n)
{
// base case
if ($n == 0)
return 0;
else
// if last bit set
// add 1 else add 0
return ($n & 1) +
countSetBits($n >> 1);
}
// Driver code
// get value from user
$n = 9;
// function calling
echo countSetBits($n);
// This code is contributed by m_kit.
?>
<button class="vote-this" data-type="like" style="margin-right:0;margin-left:0">
Gostar</button>
Artigos Recomendados
Página :
Artigo contribuído por:
Vote na dificuldade
<button class="btn" data-gfg-action="article-difficulty" data-rating="1">Fácil</button>
<button class="btn" data-gfg-action="article-difficulty" data-rating="2">Normal</button>
<button class="btn" data-gfg-action="article-difficulty" data-rating="3">Médio</button>
<button class="btn" data-gfg-action="article-difficulty" data-rating="4">Duro</button>
<button class="btn" data-gfg-action="article-difficulty" data-rating="5">Especialista</button>
Tags de artigo:
As postagens do blog Acervo Lima te ajudaram? Nos ajude a manter o blog no ar!
Faça uma doação para manter o blog funcionando.
70% das doações são no valor de R$ 5,00...
Diógenes Lima da Silva