 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
 