Count trailing zero bits using lookup table
Given an integer, count the number of trailing zeroes. For example, for n = 12, its binary representation is 1100 and number of trailing zero bits is 2.
Examples:
Input : 8
Output : 3
Binary of 8 is 1000, so there are theree
trailing zero bits.
Input : 18
Output : 1
Binary of 10 is 10010, so there is one
trailing zero bit.
A simple solution is to traverse bits from LSB (Least Significant Bit) and increment count while bit is 0.
// Simple C++ code for counting trailing zeros
// in binary representation of a number
#include<bits/stdc++.h>
using namespace std;
int countTrailingZero(int x)
{
int count = 0;
while ((x & 1) == 0)
{
x = x >> 1;
count++;
}
return count;
}
// Driver Code
int main()
{
cout << countTrailingZero(11) << endl;
return 0;
}
Output :
4
Given an integer, count the number of trailing zeroes. For example, for n = 12, its binary representation is 1100 and number of trailing zero bits is 2.
Examples:
Input : 8
Output : 3
Binary of 8 is 1000, so there are theree
trailing zero bits.
Input : 18
Output : 1
Binary of 10 is 10010, so there is one
trailing zero bit.
A simple solution is to traverse bits from LSB (Least Significant Bit) and increment count while bit is 0.
// Simple C++ code for counting trailing zeros
// in binary representation of a number
#include<bits/stdc++.h>
using namespace std;
int countTrailingZero(int x)
{
int count = 0;
while ((x & 1) == 0)
{
x = x >> 1;
count++;
}
return count;
}
// Driver Code
int main()
{
cout << countTrailingZero(11) << endl;
return 0;
}
Output :
4
No comments:
Post a Comment