C Program to count trailing zeros using bitwise operator
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | #include<stdio.h> #include<conio.h> //Display integer number into binary using bitwise operator void printBinary(int num) { int mask = 0x4000; if ((num & 0x8000) == 0) printf("0"); else printf("1"); while (mask != 0) { if ((num & mask) == 0) printf("0"); else printf("1"); mask = mask >> 1; } } void main() { int i, count = 0; unsigned int num; printf("\nEnter the number:"); scanf("%d", &num); printf("\nDecimal number in binary format :"); printBinary(num); while (num != 0) { if (num & 1 == 1) { break; } else { count++; num = num >> 1; } } printf("\nTrailing Zeros : %d", count); getch(); } |
Output:
1 2 3 | Enter the number:120 Decimal number in binary format :0000000001111000 Trailing Zeros : 3 |
lets run this program one more time -
1 2 3 | Enter the number:345 Decimal number in binary format :0000000101011001 Trailing Zeros : 0 |