Java Integer.numberofLeadingZeros()
方法
原文:https://www.studytonight.com/java-wrapper-class/java-integer-numberofleadingzeros-method
Java numberofLeadingZeros()
方法是java.lang
包的Integer
类的一部分。此方法用于返回作为参数传递的整数值的二进制补码的最高一位(最左边)之前的零位。换句话说,它将 int 值转换为二进制,并返回最高(最左边)一位之前的零位总数。
如果传递的值没有一位,即该值为零,则返回值 32。
语法:
public static int numberOfLeadingZeros(int i)
参数:
传递的参数是整数值,它的二进制补码零位在最高一位之前返回。
返回:
返回参数二进制补码的最高一位(最左边)之前的零位。
例 1:
这里,为了更好地理解该方法,取一个正数和一个负数。
Integer.toBinaryString
方法用于表示传递数的等价二进制形式。
import java.lang.*;
public class StudyTonight
{
public static void main(String[] args)
{
int i = 170; //positive number
System.out.println("Original Number is " + i);
System.out.println("Binary representation is = " + Integer.toBinaryString(i)); // converting into binary string of base 2
System.out.println("Number of leading zeros is " + Integer.numberOfLeadingZeros(i)); //returns the number of zero bits preceding the highest-order one bit
int j=-57; //negative number
System.out.println("Original Number is " + j);
System.out.println("Binary representation is = " + Integer.toBinaryString(j)); // converting into binary string of base 2
System.out.println("Number of leading zeros is " + Integer.numberOfLeadingZeros(j)); //returns the number of zero bits preceding the highest-order one bit
}
}
原数为 170 二进制表示为= 10101010 前导零数为 24 原数为-57 二进制表示为= 111111111111111111000111 前导零数为 0
例 2:
这里有一个用户定义的例子,任何使用这段代码的人都可以输入自己选择的值,并获得等效的输出。
import java.lang.*;
import java.util.Scanner;
public class StudyTonight
{
public static void main(String[] args)
{
try
{
System.out.println("Enter the number ");
Scanner sc = new Scanner(System.in);
int i=sc.nextInt();
System.out.println("Binary representation is = " + Integer.toBinaryString(i)); // converting into binary string of base 2
System.out.println("Number of leading zeros is " + Integer.numberOfLeadingZeros(i)); //returns the number of zero bits preceding the highest-order one bit
}
catch(Exception e)
{
System.out.println("Invalid input");
}
}
}
输入数字 67 二进制表示为= 1000011 前导零的个数为 25
- *输入数字 0x779 无效
实时示例:
在这里,您可以测试实时代码示例。您可以为不同的值执行示例,甚至可以编辑和编写您的示例来测试 Java 代码。