Example:
Input any number: 22
Output trailing zeros: 1
Required knowledge:
Basic C programming, Bitwise operator, If else, LoopLogic:
Counting trailing zeros in a binary number is an easy task if you know how to find first set bit in a binary number. As total number of trailing zeros is equal to the order of the first set bit.Program:
/** * C program to count trailing zeros in a binary number using bitwise operator */ #include <stdio.h> #define INT_SIZE sizeof(int) * 8 int main() { int num, count=0, i; //Reads a number from user printf("Enter any number: "); scanf("%d", &num); //Iterate over each bit of the number for(i=0; i<INT_SIZE; i++) { //If a set bit is found if((num >> i ) & 1) { //No need to run further break; } count++; } printf("Total number of trailing zeros in %d is %d.", num, count); return 0; }
Program: Another approach
/** * C program to count trailing zeros in a binary number using bitwise operator */ #include <stdio.h> int main() { int num, count=0; //Reads a number from user printf("Enter any number: "); scanf("%d", &num); while(!(num & 1)) { count++; num >>= 1; } printf("Total number of trailing zeros = %d.", count); return 0; }
Output
Enter any number: 48
Total number of trailing zeros in 48 is 4.
Total number of trailing zeros in 48 is 4.
Happy coding ;)
You may also like
- Bitwise operator programming exercises index.
- C program to count leading zeros in a binary number.
- C program to check Least Significant Bit (LSB) of a number is set or not.
- C program to check Most Significant Bit (MSB) of a number is set or not.
- C program to get nth bit of a number.
- C program to set nth bit of a number.
- C program to clear nth bit of a number.
- C program to toggle nth bit of a number.
- C program to flip bits of a binary number using bitwise operator.
- C program to total number of zeros and ones in a binary number.
- C program to convert decimal to binary number system using bitwise operator.
- C program to swap two numbers using bitwise operator.
- C program to check whether a number is even or odd using bitwise operator.