Count unset bits of a number
Last Updated :
21 Jun, 2022
Given a number n, count unset bits after MSB (Most Significant Bit).
Examples :
Input : 17
Output : 3
Binary of 17 is 10001
so unset bit is 3
Input : 7
Output : 0
A Simple Solution is to traverse through all bits and count unset bits.
C++
#include <iostream>
using namespace std;
int countunsetbits( int n)
{
int count = 0;
for ( int x = 1; x <= n; x = x<<1)
if ((x & n) == 0)
count++;
return count;
}
int main()
{
int n = 17;
cout << countunsetbits(n);
return 0;
}
|
Java
class GFG {
public static int countunsetbits( int n)
{
int count = 0 ;
for ( int x = 1 ; x <= n; x = x<< 1 )
if ((x & n) == 0 )
count++;
return count;
}
public static void main(String[] args)
{
int n = 17 ;
System.out.println(countunsetbits(n));
}
}
|
Python3
def countunsetbits(n):
count = 0
x = 1
while (x < n + 1 ):
if ((x & n) = = 0 ):
count + = 1
x = x << 1
return count
if __name__ = = '__main__' :
n = 17
print (countunsetbits(n))
|
C#
using System;
class GFG {
public static int countunsetbits( int n)
{
int count = 0;
for ( int x = 1; x <= n; x = x << 1)
if ((x & n) == 0)
count++;
return count;
}
public static void Main()
{
int n = 17;
Console.Write(countunsetbits(n));
}
}
|
PHP
<?php
function countunsetbits( $n )
{
$count = 0;
for ( $x = 1; $x <= $n ;
$x = $x << 1)
if (( $x & $n ) == 0)
$count ++;
return $count ;
}
$n = 17;
echo countunsetbits( $n );
?>
|
Javascript
<script>
function countunsetbits(n)
{
var count = 0;
for ( var x = 1; x <= n; x = x<<1)
if ((x & n) == 0)
count++;
return count;
}
var n = 17;
document.write(countunsetbits(n));
</script>
|
Output :
3
Above solution complexity is log(n).
Space Complexity : O(1)
Efficient Solutions :
The idea is to toggle bits in O(1) time. Then apply any of the methods discussed in count set bits article.
In GCC, we can directly count set bits using __builtin_popcount(). First toggle the bits and then apply above function __builtin_popcount().
C++
#include <iostream>
using namespace std;
int countUnsetBits( int n)
{
int x = n;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
return __builtin_popcount(x ^ n);
}
int main()
{
int n = 17;
cout << countUnsetBits(n);
return 0;
}
|
Java
class GFG
{
static int countUnsetBits( int n)
{
int x = n;
n |= n >> 1 ;
n |= n >> 2 ;
n |= n >> 4 ;
n |= n >> 8 ;
n |= n >> 16 ;
return Integer.bitCount(x^ n);
}
public static void main(String[] args)
{
int n = 17 ;
System.out.println(countUnsetBits(n));
}
}
|
Python3
import math
def countUnsetBits(n):
x = n
n | = n >> 1
n | = n >> 2
n | = n >> 4
n | = n >> 8
n | = n >> 16
t = math.log(x ^ n, 2 )
return math.floor(t)
n = 17
print (countUnsetBits(n))
|
C#
PHP
Javascript
Output :
3
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...