# 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 totalBits = sizeof(n) * 8;
string binary = "";
while (n) {
int remainder = n % 2;
if (remainder || binary.length() > 0) {
binary += remainder;
}
n /= 2;
}
}
int main() {
int n = 101;
}
25