- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
Count number of trailing zeros in Binary representation of a number using Bitset in C++
Given an integer num as input. The goal is to find the number of trailing zeroes in the binary representation of num using bitset.
A bitset stores the bits 0s and 1s in it. It is an array of bits.
For Example
Input
num = 10
Output
Count of number of trailing zeros in Binary representation of a number using Bitset are: 1
Explanation
The number 10 in binary is represented as 1010 so trailing zeroes in it is 1.
Input
num = 64
Output
Count of number of trailing zeros in Binary representation of a number using Bitset are: 6
Explanation
The number 64 in binary is represented as 10000000 so trailing zeroes in it is 6.
Approach used in the below program is as follows −
In this approach we are using bitset. We will set the bitset with num using |. Now traverse bitset using for loop, as soon as the first 1 is encountered then break the loop otherwise increment count for trailing zeroes.
Take an integer num as input.
Function trailing_zeroes(int num) takes num and returns the count of number of trailing zeros in Binary representation of a number using Bitset.
Take the initial count as 0.
Take a bitset arr.
Set it with num as arr |=num.
Traverse arr using for loop from i=0 to i<64. If arr[i] is 0 then increment count else breaks the loop.
Return count as result at the end of loop.
Example
#include <bits/stdc++.h> using namespace std; int trailing_zeroes(int num){ int count = 0; bitset<64> arr; arr |= num; for (int i = 0; i < 64; i++){ if (arr[i] == 0){ count++; } else { break; } } return count; } int main(){ int num = 6; cout<<"Count of number of trailing zeros in Binary representation of a number using Bitset are: "<<trailing_zeroes(num); return 0; }
Output
If we run the above code it will generate the following output −
Count of number of trailing zeros in Binary representation of a number using Bitset are: 1