- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
- Related Articles
- Binary representation of a given number in C++
- Count number of trailing zeros in Binary representation of a number using Bitset in C++
- C Program to count trailing and leading zeros in a binary number
- Binary representation of next number in C++
- Binary representation of previous number in C++
- Number of Steps to Reduce a Number in Binary Representation to One in C++
- Prime Number of Set Bits in Binary Representation in C++
- Find consecutive 1s of length >= n in binary representation of a number in C++
- How to remove leading zeros from a number in JavaScript?
- How to pad a number with leading zeros in JavaScript?
- Java Program to add leading zeros to a number
- Prime Number of Set Bits in Binary Representation in Python
- Check if binary representation of a number is palindrome in Python
- Binary representation of next greater number with same number of 1’s and 0’s in C Program?
- C++ Representation of a Number in Powers of Other

Advertisements