當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Integer numberOfLeadingZeros()用法及代碼示例


numberOfLeadingZeros() 方法是java.lang 包下Integer 類的一個方法。此方法返回指定整數值的二進製補碼表示中 highest-order ("leftmost") one-bit 之前的零位總數,即將 int 值轉換為 Binary 然後考慮最高一位並返回其前麵的零位總數。換句話說,如果指定的整數值沒有 one-bits 或在其二進製補碼表示中等於 0,則它將返回 32。

注意:此方法與以 2 為底的對數密切相關。對於所有正整數值 x:

floor(log2(x)) = 31 - numberOfLeadingZeros(x)
ceil(log2(x)) = 32 - numberOfLeadingZeros(x - 1).

說明:

Suppose, Integer Value = 55 
Binary Equivalent = 110111
Highest(Left-Most Bit) = 100000 i.e. at position 6
numberOfLeadingZeros = It will return in 32-bit representation, so preceding zero's are ( 32 - 6 = 26 ).

用法:

以下是 numberOfLeadingZeros() 方法的聲明:

public static int numberOfLeadingZeros(int i)

參數:

數據類型 參數 描述 必需/可選
int i 它接受整數值,該值返回其 2 的補碼的最高位。 Required

返回值:

numberOfLeadingZeros() 方法返回指定整數值的二進製補碼表示中 highest-order ("leftmost") one-bit 之前的零位數,如果該值等於零,則返回 32。

異常:

NA

兼容版本:

Java 1.5 及以上

例子1

public class IntegerNumberOfLeadingZerosExample1 {
	public static void main(String[] args) {
	System.out.println("Leading Zero's:"+Integer.numberOfLeadingZeros(10));       
    }
}

輸出:

Leading Zero's:28

例子2

public class IntegerNumberOfLeadingZerosExample2 {
	public static void main(String[] args) {
		int value = 55;
		//Get the binary equivalent of this Integer value
		System.out.print("Binary equivalent:"+Integer.toBinaryString(value));
		//Print the number of Leading zeros
		System.out.print("\nNumber of Leading Zeros:"+Integer.numberOfLeadingZeros(value));
    }
}

輸出:

Binary equivalent:110111
Number of Leading Zeros:26

例子3

import java.util.Scanner;
public class IntegerNumberOfLeadingZerosExample3 {
	public static void main(String[] args) {
		//Get Numeric value from Console
		System.out.print("Enter the desired Integer value:");
		Scanner readInput = new Scanner(System.in);
		int value = readInput.nextInt();
		readInput.close();
		//Get the binary equivalent of this Integer value
		System.out.print("Binary equivalent:"+Integer.toBinaryString(value));
		//Print the number of leading zeros
		System.out.print("\nNumber of Leading Zeros:"+Integer.numberOfLeadingZeros(value));
    }
}

輸出:

Enter the desired Integer value:75
Binary equivalent:1001011
Number of Leading Zeros:25

示例 4

public class IntegerNumberOfLeadingZerosExample4 {
	public static void main(String[] args) {
	  int num = -15;
        System.out.print("Input Number = " + num);
        // Returns the number of zero bits preceding the highest leftmost one-bit
        System.out.print("\nNumber of Leading Zeros = "+Integer.numberOfLeadingZeros(num));       
    }
}

輸出:

Input Number = -15
Number of Leading Zeros = 0

例 5

public class IntegerNumberOfLeadingZerosExample5 {
	public static void main(String[] args) {
	System.out.println("Leading Zero's:"+Integer.numberOfLeadingZeros(0));       
    }
}

輸出:

Leading Zero's:32






相關用法


注:本文由純淨天空篩選整理自 Java Integer numberOfLeadingZeros() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。