Java Integer rotateLeft 메서드

JavaBeginner
지금 연습하기

소개

Java 의 rotateLeft() 메서드는 java.lang 패키지의 Integer 클래스에 내장된 메서드입니다. 이 랩에서는 정수의 이진 표현에 해당하는 비트를 회전시키는 데 사용되는 rotateLeft() 메서드를 사용하는 방법을 배우게 됩니다. 즉, 이진수의 모든 비트가 특정 횟수만큼 왼쪽 또는 오른쪽으로 시프트됩니다.

음수에 rotateLeft() 메서드 사용하기

  1. 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 메서드는 정수의 이진 표현을 얻는 데 사용됩니다.

  2. 파일을 저장하고 텍스트 편집기를 닫습니다.

  3. 다음 명령을 사용하여 코드를 컴파일합니다.

    javac ~/project/RotateLeft.java
  4. 다음 명령을 사용하여 코드를 실행합니다.

    java -cp ~/project RotateLeft
  5. 출력에서 원래 정수의 이진 표현, 지정된 횟수만큼 왼쪽으로 회전한 후의 새 숫자의 십진수 표현, 그리고 새 숫자의 이진 표현을 볼 수 있습니다.

사용자 정의 숫자에 rotateLeft() 메서드 사용하기

  1. 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));
        }
    }
  2. 파일을 저장하고 텍스트 편집기를 닫습니다.

  3. 다음 명령을 사용하여 코드를 컴파일합니다.

    javac ~/project/RotateLeft.java
  4. 다음 명령을 사용하여 코드를 실행합니다.

    java -cp ~/project RotateLeft
  5. 프롬프트가 표시되면 정수와 비트를 왼쪽으로 회전시킬 비트 위치의 수를 입력합니다.

  6. 출력에서 원래 정수의 이진 표현, 지정된 횟수만큼 왼쪽으로 회전한 후의 새 숫자의 십진수 표현, 그리고 새 숫자의 이진 표현을 볼 수 있습니다.

요약

이 랩에서는 Integer 클래스의 rotateLeft() 메서드를 사용하여 정수의 이진 표현의 비트를 회전시키는 방법을 배웠습니다. 이를 통해 원래 정수의 이진 표현과 회전 후의 새 숫자의 이진 표현을 출력할 수 있습니다. 다양한 값을 실행함으로써 rotateLeft() 메서드가 정수의 이진 표현의 모든 비트를 왼쪽으로 어떻게 이동시키는지 관찰할 수 있습니다.