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

C++Server Side ProgrammingProgramming

Given a number, we have to find the number of leading zeroes in the binary representation of it. Assuming total bits to be 32. Let's see an example.

Input

5

Output

25

The binary representation of 5 is 00000...00101. The number of leading zeroes are 29.

Algorithm

  • Initialise the number n.
  • Find the binary representation of n.
  • Subtract the length of binary representation of n from the total number of bits i.e.., 32.
  • Return the result.

Implementation

Following is the implementation of the above algorithm in C++

#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;
}

Output

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

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

Advertisements