Count unset bits of a number - GeeksforGeeks

29 Apr, 2021
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++
Java
Python3
C#
PHP
Javascript
// C++ program to count unset bits in an integer#include <iostream>using namespace std; int countunsetbits(int n){    int count = 0;         // x holds one set digit at a time    // starting from LSB to MSB of n.    for (int x = 1; x <= n; x = x<<1)        if ((x & n) == 0)            count++;         return count;} // Driver codeint main(){    int n = 17;    cout << countunsetbits(n);    return 0;}
// JAVA Code to Count unset bits in a numberclass GFG {     public static int countunsetbits(int n)    {        int count = 0;                  // x holds one set digit at a time        // starting from LSB to MSB of n.        for (int x = 1; x <= n; x = x<<1)            if ((x & n) == 0)                count++;                  return count;    }         /* Driver program to test above function */    public static void main(String[] args)    {        int n = 17;        System.out.println(countunsetbits(n));    }}// This code is contributed by Arnav Kr. Mandal.
# Python 3 program to count unset# bits in an integer def countunsetbits(n):    count = 0         # x holds one set digit at a time    # starting from LSB to MSB of n.    x = 1    while(x < n + 1):        if ((x & n) == 0):            count += 1        x = x << 1     return count # Driver codeif __name__ == '__main__':    n = 17    print(countunsetbits(n))     # This code is contributed by# Shashank_Sharma
// C# Code to Count unset// bits in a numberusing System; class GFG {     // Function to count unset bits    public static int countunsetbits(int n)    {        int count = 0;                 // x holds one set digit at a time        // starting from LSB to MSB of n.        for (int x = 1; x <= n; x = x << 1)            if ((x & n) == 0)                count++;                 return count;    }         // Driver Code    public static void Main()    {        int n = 17;        Console.Write(countunsetbits(n));    }} // This code is contributed by Nitin Mittal.
<?php// PHp program to count// unset bits in an integerfunction countunsetbits($n){    $count = 0;         // x holds one set digit    // at a time starting    // from LSB to MSB of n.    for ($x = 1; $x <= $n;         $x = $x << 1)        if (($x & $n) == 0)            $count++;         return $count;} // Driver code$n = 17;echo countunsetbits($n); // This code is contributed// by nitin mittal.?>
<script> // Javascript program to count unset bits in an integer function countunsetbits(n){    var count = 0;         // x holds one set digit at a time    // starting from LSB to MSB of n.    for (var x = 1; x <= n; x = x<<1)        if ((x & n) == 0)            count++;         return count;} // Driver codevar n = 17;document.write(countunsetbits(n)); </script>
Output : 
3
Above solution complexity is log(n).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++
Java
Python3
C#
PHP
Javascript
// An optimized C++ program to count unset bits// in an integer.#include <iostream>using namespace std; int countUnsetBits(int n){    int x = n;      // Make all bits set MSB     // (including MSB)       // This makes sure two bits    // (From MSB and including MSB)    // are set    n |= n >> 1;     // This makes sure 4 bits    // (From MSB and including MSB)    // are set    n |= n >> 2;     n |= n >> 4;    n |= n >> 8;    n |= n >> 16;     // Count set bits in toggled number    return  __builtin_popcount(x ^ n);} // Driver codeint main(){    int n = 17;    cout << countUnsetBits(n);    return 0;}
// An optimized Java program to count unset bits// in an integer.class GFG{ static int countUnsetBits(int n){    int x = n;     // Make all bits set MSB    // (including MSB)         // This makes sure two bits    // (From MSB and including MSB)    // are set    n |= n >> 1;     // This makes sure 4 bits    // (From MSB and including MSB)    // are set    n |= n >> 2;     n |= n >> 4;    n |= n >> 8;    n |= n >> 16;     // Count set bits in toggled number    return Integer.bitCount(x^ n);} // Driver codepublic static void main(String[] args){    int n = 17;    System.out.println(countUnsetBits(n));}} /* This code contributed by PrinciRaj1992 */
# An optimized Python program to count# unset bits in an integer.import math def countUnsetBits(n):    x = n     # Make all bits set MSB(including MSB)     # This makes sure two bits(From MSB    # and including MSB) are set    n |= n >> 1     # This makes sure 4 bits(From MSB and    # including MSB) are set    n |= n >> 2     n |= n >> 4    n |= n >> 8    n |= n >> 16     t = math.log(x ^ n, 2)     # Count set bits in toggled number    return math.floor(t) # Driver coden = 17print(countUnsetBits(n)) # This code is contributed 29AjayKumar
// An optimized C# program to count unset bits// in an integer.using System; class GFG{ static int countUnsetBits(int n){    int x = n;     // Make all bits set MSB    // (including MSB)         // This makes sure two bits    // (From MSB and including MSB)    // are set    n |= n >> 1;     // This makes sure 4 bits    // (From MSB and including MSB)    // are set    n |= n >> 2;     n |= n >> 4;    n |= n >> 8;    n |= n >> 16;     // Count set bits in toggled number    return BitCount(x^ n);} static int BitCount(long x){     // To store the count    // of set bits    int setBits = 0;    while (x != 0) {        x = x & (x - 1);        setBits++;    }     return setBits;} // Driver codepublic static void Main(String[] args){    int n = 17;    Console.WriteLine(countUnsetBits(n));}} // This code contributed by Rajput-Ji
<?php// An optimized PHP program// to count unset bits in// an integer. function countUnsetBits($n){    $x = $n;     // Make all bits set     // MSB(including MSB)     // This makes sure two    // bits(From MSB and    // including MSB) are set    $n |= $n >> 1;     // This makes sure 4    // bits(From MSB and    // including MSB) are set    $n |= $n >> 2;     $n |= $n >> 4;    $n |= $n >> 8;    $n |= $n >> 16;     $t = log($x ^ $n,2);         // Count set bits    // in toggled number    return floor($t);} // Driver code$n = 17;echo countUnsetBits($n); // This code is contributed// by ajit?>
<script> // JavaScript program to count unset bits// in an integer. function countUnsetBits(n){    let x = n;      // Make all bits set MSB    // (including MSB)          // This makes sure two bits    // (From MSB and including MSB)    // are set    n |= n >> 1;      // This makes sure 4 bits    // (From MSB and including MSB)    // are set    n |= n >> 2;      n |= n >> 4;    n |= n >> 8;    n |= n >> 16;      // Count set bits in toggled number    return BitCount(x^ n);} function BitCount(x){      // To store the count    // of set bits    let setBits = 0;    while (x != 0) {        x = x & (x - 1);        setBits++;    }      return setBits;} // Driver Code     let n = 17;    document.write(countUnsetBits(n)); // This code is contributed by susmitakundugoaldanga.</script>
Output :  
3
This article is contributed by Devanshu Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
nitin mittal
jit_t
29AjayKumar
Shashank_Sharma
princiraj1992
Rajput-Ji
rrrtnx
susmitakundugoaldanga
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Cyclic Redundancy Check and Modulo-2 Division
Bit Fields in C
Add two numbers without using arithmetic operators
Find the element that appears once
Bits manipulation (Important tactics)
Set, Clear and Toggle a given bit of a number in C
C++ bitset and its application
1's and 2's complement of a Binary Number
Find the Number Occurring Odd Number of Times
Divide two integers without using multiplication, division and mod operator