- Related Questions & Answers
- Count number of trailing zeros in Binary representation of a number using Bitset in C++
- Count trailing zeros in factorial of a number in C++
- Number of leading zeros in binary representation of a given number in C++
- Java Program to add leading zeros to a number
- Count number of trailing zeros in product of array in C++
- Java Program to remove leading and trailing whitespace from a string
- C/C++ Program to Count trailing zeroes in factorial of a number?
- Trim (Remove leading and trailing spaces) a string in C#
- Add leading Zeros to Python Program string
- How to remove leading zeros from a number in JavaScript?
- How to pad a number with leading zeros in JavaScript?
- Java Program to remove the leading and trailing quotes from a string
- Remove Leading Zeros from a String in C#
- Add trailing Zeros to a Python string
- Python Program to Count trailing zeroes in factorial of a number

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

To begin with, let us understand what are trailing zeros in a binary number.

The position of zeros after first one from the least significant bit (LSB) is called as trailing zeros in binary number.

104 is decimal number

Binary number of 104 is: (MSB) 1101000(LSB)

Here,

- MSB refers to Most Significant Bit.
- LSB refers to Least Significant Bit.
- From LSB after the first bit set, there are three zero.
- The number of trailing zeros is three.

Following is the program to count number of trailing zeros for a given number −

#include<stdio.h> #include<stdlib.h> int main(){ int number, i, trail = 0, size; printf("Enter a number\n"); scanf("%d",&number); size = sizeof(number) * 8; for(i = 0; i < size; i++){ if((number >> i) & 1) { break; } trail++; } printf("Number of trailing ZERO is = %d", trail); return 0; }

When the above program is executed, it produces the following result −

Enter a number 24 Number of trailing ZERO is = 3

If the position of zero **before bit is set to one**, they are termed as leading zeros.

94 is decimal number.

Binary number of 94 is: (MSB) .....001011110(LSB)

Number of Leading ZERO is = 25

Given below is the program to count number of leading zeros for a given number.

#include<stdio.h> #include<stdlib.h> int main(){ int number, i, lead = 0, Msb,size; printf("Enter a number\n"); scanf("%d",&number); size = sizeof(number) * 8; Msb=1<<(size-1); for(i = 0; i < size; i++){ if((number << i) & Msb) { break; } lead++; } printf("Number of Leading ZERO is = %d", lead); return 0; }

When the above program is executed, it produces the following result −

Enter a number 94 Number of Leading ZERO is = 25

Advertisements