- Related Questions & Answers
- Count trailing zeros in factorial of a number in C++
- Number of leading zeros in binary representation of a given number in C++
- Count number of trailing zeros in product of array in C++
- C Program to count trailing and leading zeros in a binary number
- Binary representation of a given number in C++
- Binary representation of next number in C++
- Binary representation of previous number in C++
- Count number of trailing zeros in (1^1)*(2^2)*(3^3)*(4^4)*.. 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++
- C/C++ Program to Count trailing zeroes in factorial of a number?
- C/C++ Programming to Count trailing zeroes in factorial of a number?
- Maximum number of trailing zeros in the product of the subsets of size k in C++
- Sorting according to number of 1s in binary representation using JavaScript
- Python Program to Count trailing zeroes in factorial of a number

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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**

num = 10

Count of number of trailing zeros in Binary representation of a number using Bitset are: 1

The number 10 in binary is represented as 1010 so trailing zeroes in it is 1.

num = 64

Count of number of trailing zeros in Binary representation of a number using Bitset are: 6

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.

#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; }

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

Advertisements