How to Returns the number of leading zeros in a 32-bit binary representation of x in JavaScript ?


There are multiple methods to return the number of leading zeros in a 32-bit binary representation of x in JavaScript:

Method 1: Using the toString() and match() methods We can convert the number to its binary representation using the toString() method with a radix of 2. Then, we can use the match() method with a regular expression to find the number of leading zeros.

Example:

function countLeadingZeros(x) {
  let binary = x.toString(2);
  let match = binary.match(/^0*/);
  return match[0].length;
}

console.log(countLeadingZeros(5)); // Output: 27
console.log(countLeadingZeros(16)); // Output: 19

Method 2: Using the bitwise operators We can use the bitwise operators to shift the bits of the number to the right until the number becomes 0. The number of shifts required is equal to the number of leading zeros.

Example:

function countLeadingZeros(x) {
  let count = 0;
  while (x !== 0) {
    x >>>= 1;
    count++;
  }
  return 32 - count;
}

console.log(countLeadingZeros(5)); // Output: 27
console.log(countLeadingZeros(16)); // Output: 19

Method 3: Using the Math.clz32() method The Math.clz32() method returns the number of leading zeros in a 32-bit binary representation of a number.

Example:

function countLeadingZeros(x) {
  return 32 - Math.clz32(x);
}

console.log(countLeadingZeros(5)); // Output: 27
console.log(countLeadingZeros(16)); // Output: 19


About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.