当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。