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


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


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

說明:

Suppose, Integer Value = 52
Binary Equivalent = 110100
Lowest(Right-Most Bit) =  At position 3
numberOfTrailingZeros = 2

用法:

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

public static int numberOfTrailingZeros(int i)

參數:

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

返回值:

numberOfTrailingZeros() 方法返回指定整數值的二進製補碼表示中最低階 ("rightmost") one-bit 之後的零位數,如果該值等於零,則返回 32。

異常:

NA

兼容版本:

Java 1.5 及以上

例子1

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

輸出:

Trailing Zero's:1

例子2

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

輸出:

Binary equivalent:111000
Number of Trailing Zeros:3

例子3

import java.util.Scanner;
public class IntegerNumberOfTrailingZerosExample3 {
	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 Trailing zeros
		System.out.print("\nNumber of Trailing Zeros:"+Integer.numberOfTrailingZeros(value));
    }
}

輸出:

Enter the desired Integer value:52
Binary equivalent:110100
Number of Trailing Zeros:2

示例 4

public class IntegerNumberOfTrailingZerosExample4 {
	public static void main(String[] args) {
	  int num = -15;
        System.out.print("Input Number = " + num);
        // Returns the number of zero bits following the Lowest rightmost one-bit
        System.out.print("\nNumber of Trailing Zeros = "+Integer.numberOfTrailingZeros(num));       
    }
}

輸出:

Input Number = -15
Number of Trailing Zeros = 0

例 5

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

輸出:

Trailing Zero's:32






相關用法


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