Java Integer.numberofTrailingZeros()方法

原文:https://www.studytonight.com/java-wrapper-class/java-integer-numberoftrailingzeros-method

Java numberofTrailingZeros()方法是java.lang包的Integer类的一部分。此方法用于返回作为参数传递的整数值的二进制补码的最低一位(最右边)之后的零位。换句话说,它将 int 值转换为二进制,并返回最低(最右边)一位之后的零位总数。

如果传递的值没有一位,即该值为零,则返回值 32。

语法:

public static int numberOfTrailingZeros(int i)

参数:

传递的参数是一个整数值,它的零位数跟在返回的最低位之后。

返回:

返回所传递参数的最低一位(最右边)之后的零位数。

例 1:

这里,为了更好地理解该方法,取一个正数和一个负数。

Integer.toBinaryString方法用于表示传递数的等价二进制形式。

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)); 
      System.out.println("Number of trailing zeros is " + Integer.numberOfTrailingZeros(i)); 
      //returns the number of zero bits following the lowest-order one bit

      int j=-57; //negative number
      System.out.println("Original Number is " + j);
      System.out.println("Binary representation is = " + Integer.toBinaryString(j)); 
      System.out.println("Number of trailing zeros is " + Integer.numberOfTrailingZeros(j)); 
      //returns the number of zero bits following the lowest-order one bit
   }
}

原数为 170 二进制表示为= 10101010 尾随零数为 1 原数为-57 二进制表示为= 1111111111111111111000111 前导零数为 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)); 
        System.out.println("Number of trailing zeros is " + Integer.numberOfTrailingZeros(i)); 
        //returns the number of zero bits following the lowest-order one bit
      }
      catch(Exception e)
      {
        System.out.println("Invalid input");
      }
   }
}

输入数字 87 二进制表示为= 1010111 尾随零的个数为 0 *输入数字 0x324 无效

实时示例:

在这里,您可以测试实时代码示例。您可以为不同的值执行示例,甚至可以编辑和编写您的示例来测试 Java 代码。