C Program to count trailing zeros of a number using bitwise operator

  • C program to count trailing zeros in binary representation of a number using bitwise operator

Required knowledge: Bitwise operators.
Algorithm to count trailing zero bits in a number.
  • Check whether least significant bit of a number(N) is 0 or not by doing bitwise And(&) with 1. if (N & 1) == 0, that means last bit is 0 otherwise 1.
  • If last bit is 0, then increment a counter and right shift N by one bit position.
  • Repeat above steps until (N & 1) == 1 or N ==0.

C Program to count trailing zeros of a number using bitwise operator

#include<stdio.h>
#include<stdlib.h>

int main() {
   int num, count = 0;
   char str[100];
   printf("Enter an integer\n");
   scanf("%d", &num);
 
   /* Convert integer to a binary number using 
      atoi and store it in a string */
   itoa(num, str, 2);
   printf("Binary Number : %s\n", str);
   /* count number of trailing zero's in binary 
      representation of num */
   while (num != 0) {
      if (num & 1 == 1) {
         break;
      } else {
         count++;
         num = num >> 1;
      }
   }
   printf("Number of Trailing Zeros = %d", count);
   
   return 0;
}
Output
Enter an integer
60
Binary Number : 111100
Number of Trailing Zeros = 2
Enter an integer
15
Binary Number : 1111
Number of Trailing Zeros = 0