介绍
Java 的 rotateLeft() 方法是 java.lang 包中 Integer 类的一个内置方法。在本实验中,你将学习如何使用 rotateLeft() 方法,该方法用于旋转整数二进制表示的位,即将二进制数的所有位向左或向右移动一定的位数。
在负数上使用 rotateLeft() 方法
在
RotateLeft.java文件中,修改 Java 代码以包含一个负数。假设整数为-10,编写以下代码:public class RotateLeft { public static void main(String[] args) { int n = -10; int value = 4; System.out.println("Binary equivalent of " + n + " is: " + Integer.toBinaryString(n)); n = Integer.rotateLeft(n, value); //rotate left value times System.out.println("After rotating " + value + " times to the left, the decimal number is: " + n); System.out.println("Binary equivalent of the new number is: " + Integer.toBinaryString(n)); } }注意:
toBinaryString方法用于获取整数的二进制表示。保存文件并关闭文本编辑器。
使用以下命令编译代码:
javac ~/project/RotateLeft.java使用以下命令执行代码:
java -cp ~/project RotateLeft在输出中,你应该会看到原始整数的二进制表示、向左旋转指定次数后的新整数的十进制表示,以及新整数的二进制表示。
为用户自定义的数字使用 rotateLeft() 方法
在
RotateLeft.java文件中,修改 Java 代码以接收用户自定义的整数值和要向左旋转的位数。编写如下代码:import java.util.Scanner; public class RotateLeft { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter an integer number: "); int n = input.nextInt(); System.out.print("Enter the number of times to rotate the bits to the left: "); int value = input.nextInt(); input.close(); System.out.println("Binary equivalent of " + n + " is: " + Integer.toBinaryString(n)); n = Integer.rotateLeft(n, value); //rotate left value times System.out.println("After rotating " + value + " times to the left, the decimal number is: " + n); System.out.println("Binary equivalent of the new number is: " + Integer.toBinaryString(n)); } }保存文件并关闭文本编辑器。
使用以下命令编译代码:
javac ~/project/RotateLeft.java使用以下命令执行代码:
java -cp ~/project RotateLeft当提示时,输入一个整数和要向左旋转的位数。
在输出中,你应该会看到原始整数的二进制表示、向左旋转指定次数后的新整数的十进制表示,以及新整数的二进制表示。
总结
在本实验中,你学习了如何使用 Integer 类中的 rotateLeft() 方法来旋转整数二进制表示的位,从而能够输出原始整数的二进制表示以及旋转后新整数的二进制表示。通过执行不同的值,你可以观察到 rotateLeft() 方法如何将整数二进制表示的所有位向左移动。



