VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-trailing-zero-bits-using-lookup-table/

⇱ Count trailing zero bits using lookup table - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count trailing zero bits using lookup table

Last Updated : 23 Jul, 2025

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 three
trailing zero bits.

Input : 18
Output : 1
Binary of 18 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.  

Output : 

0


Time Complexity : O(Log n)

Auxiliary Space: O(1)
 
The lookup table solution is based on following concepts : 

  1. The solution assumes that negative numbers are stored in 2's complement form which is true for most of the devices. If numbers are represented in 2's complement form, then (x & -x) [Bitwise and of x and minus x] produces a number with only last set bit.
  2. Once we get a number with only one bit set, we can find its position using lookup table. It makes use of the fact that the first 32 bit position values are relatively prime with 37, so performing a modulus division with 37 gives a unique number from 0 to 36 for each. These numbers may then be mapped to the number of zeros using a small lookup table.

Output : 

4


Time Complexity : O(1)

Auxiliary Space: O(1)
Source : 
https://graphics.stanford.edu/~seander/bithacks.html


 

Comment
Article Tags:
Article Tags: