
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Number of Leading Zeros in Binary Representation of a Given Number in C++
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
Advertisements