Java Integer.rotateLeft()方法

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

Java rotateLeft()方法是java.lang包的Integer类的一部分。此方法用于返回通过将作为参数传递的数字的二进制等价形式的二进制补码向左(即向高阶)旋转参数中指定的距离而获得的值。

该方法基于位移位操作,其中二进制数的所有位被向左或向右移位到一定数量的位置。例如,rotateLeft(10, 1)指的是 10 的二进制等效值向左旋转一位。 10 的等价二进制为 00001010 ,左移 1 位转换为 00010100 (即等于 20)。

语法:

public static int rotateLeft(int i, int distance)

参数:

传递的参数是整数值,指定要旋转的二进制等价位,以及指定要旋转的位数的 int 距离。

返回:

返回通过将作为参数传递的数字的二进制等价形式的二进制补码向左(即向高阶)旋转方法中传递的距离而获得的值。

例 1:

这里,为了更好地理解该方法,取一个正数和一个负数。Integer.toBinaryString()方法用于以二进制等价形式表示数字。

import java.lang.*;

public class StudyTonight 
{
   public static void main(String[] args)
   {
      int n1 = 4;
      int n2 = -4;
      int val = 3;      
      System.out.println("Binary equivalent is : " + Integer.toBinaryString(n1));     
      for(int i = 0; i < val; i++) 
      {
         n1 = Integer.rotateLeft(n1, val); //returns the value after rotation
         System.out.println(n1);
       }       
       System.out.println("Binary equivalent is : " + Integer.toBinaryString(n2));       
       for(int i = 0; i < val; i++) 
       {
         n2 = Integer.rotateLeft(n2, val); //returns the value after rotation
         System.out.println(n2);
       }
   }
}

二进制等值为:100 32 256 2048 二进制等值为:1111111111111111111111100 -25 -193 -1537

例 2:

这里有一个用户定义的例子,任何使用这段代码的人都可以输入自己选择的值,并获得等效的输出。

import java.lang.*;
import java.util.*;

public class StudyTonight 
{
   public static void main(String[] args)
   {
      try
      {
         System.out.println("Enter the value and distance");
         Scanner sc = new Scanner (System.in);
         int n = sc.nextInt();
         int val = sc.nextInt();         
         System.out.println("Binary equivalent is : " + Integer.toBinaryString(n));
         for(int i = 0; i < val; i++) 
         {
           n = Integer.rotateLeft(n, val); //returns the value after rotation
           System.out.println(n);
         }
      }
      catch(Exception e)
      {
        System.out.println("Invalid Input");
      }              
   }
}

输入数值和距离 5 4 二进制等效值为:101 80 1280 20480 327680

                                                    • *输入数值和距离 -30 4 二进制等效值为:11111111111111111111100010

实时示例:

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