Number of leading zeros in binary representation of a given number in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that finds the number of leading zeroes in the binary representation of the given number.

Let's see the steps to solve the problem.

  • Initialise the number n.

  • Find the total number of bits with size of int.

  • Find the binary representation of n.

  • Return the remaining bits with the binary length.


Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int getLeadingZeroesCount(unsigned int n) {
   int totalBits = sizeof(n) * 8;
   string binary = "";
   while (n) {
      int remainder = n % 2;
      if (remainder || binary.length() > 0) {
         binary += remainder;
      n /= 2;
   return totalBits - binary.length();
int main() {
   int n = 101;
   cout << getLeadingZeroesCount(n) << endl;
   return 0;


If you run the above code, then you will get the following result.



If you have any queries in the tutorial, mention them in the comment section.

Published on 03-Jul-2021 08:08:20