java.lang.Long numberOfLeadingZeros(long i)

Description

The Long.numberOfLeadingZeros(long i) java method returns the number of zero bits preceding the highest-order (“leftmost”) one-bit in the two’s complement binary representation of the specified long value. Returns 64 if the specified value has no one-bits in its two’s complement representation, in other words if it is equal to zero.

Note that this method is closely related to the logarithm base 2. For all positive long values x:

floor(log2(x)) = 63 - numberOfLeadingZeros(x)
ceil(log2(x)) = 64 - numberOfLeadingZeros(x - 1)

Make a note that the numberOfLeadingZeros() method of Long class is static thus it should be accessed statically which means the we would be calling this method in this format:

Long.numberOfLeadingZeros(method args)

Non static method is usually called by just declaring method_name(argument) however in this case since the method is static, it should be called by appending the class name as suffix. We will be encountering a compilation problem if we call the java numberOfLeadingZeros method non statically.

Method Syntax

public static int numberOfLeadingZeros(long i)

Method Argument

Data Type Parameter Description
long i the value whose number of leading zeros is to be computed

Method Returns

The numberOfLeadingZeros(long i) method of Long class returns the number of zero bits preceding the highest-order (“leftmost”) one-bit in the two’s complement binary representation of the specified long value, or 64 if the value is equal to zero.

Compatibility

Requires Java 1.5 and up

Java Long numberOfLeadingZeros(long i) Example

Below is a simple java example on the usage of numberOfLeadingZeros(long i) method of Long class.

package com.javatutorialhq.java.examples;

import java.util.Scanner;

/*
 * This example source code demonstrates the use of  
 * numberOfLeadingZeros(long i) method of Long class
 */

public class LongNumberOfLeadingZerosExample {

	public static void main(String[] args) {

		// Ask for user input
		System.out.print("Enter a value:");

		// declare a scanner object to read the user input
		Scanner s = new Scanner(System.in);

		// assign the input to a variable
		long value = s.nextLong();

		// get the numberOfLeadingZeros() method result
		int result = Long.numberOfLeadingZeros(value);

		// print the result
		System.out.println("Result:" + result);

		// close the scanner object
		s.close();

	}

}

Sample Output

Below is the sample output when you run the above example.

Java Long numberOfLeadingZeros(long i) example output