Java - Integer rotateLeft() 方法



描述

Java Integer rotateLeft() 方法返回透過將指定 int 值 i 的二進位制補碼錶示向左旋轉指定位數而獲得的值。(從左側或高位端移出的位重新進入右側或低位端)。

宣告

以下是 java.lang.Integer.rotateLeft() 方法的宣告

public static int rotateLeft(int i, int distance)

引數

  • i − 這是 int 值。

  • distance − 這是旋轉距離。

返回值

此方法返回透過將指定 int 值的二進位制補碼錶示向左旋轉指定位數而獲得的值。

異常

從正整數獲取左旋轉位整數示例

以下示例演示瞭如何使用 Integer rotateLeft() 方法透過將指定 int 值 i 的二進位制補碼錶示向左旋轉指定位數來獲取一個 int。我們建立了一個 int 變數併為其分配了一個正整數。然後在 for 迴圈中使用 rotateLeft() 方法,列印生成的新整數。

package com.tutorialspoint;
public class IntegerDemo {
   public static void main(String[] args) {
      int n = 2;

      // returns the value obtained by rotating left
      for(int i = 0; i < 4; i++) {
         n = Integer.rotateLeft(n, 4);
         System.out.println(n);
      }
   }
} 

輸出

讓我們編譯並執行以上程式,這將產生以下結果:

32
512
8192
131072

從負整數獲取左旋轉位整數示例

以下示例演示瞭如何使用 Integer rotateLeft() 方法透過將指定 int 值 i 的二進位制補碼錶示向左旋轉指定位數來獲取一個 int。我們建立了一個 int 變數併為其分配了一個負整數。然後在 for 迴圈中使用 rotateLeft() 方法,列印生成的新整數。

package com.tutorialspoint;
public class IntegerDemo {
   public static void main(String[] args) {
      int n = -2;

      // returns the value obtained by rotating left
      for(int i = 0; i < 4; i++) {
         n = Integer.rotateLeft(n, 4);
         System.out.println(n);
      }
   }
} 

輸出

讓我們編譯並執行以上程式,這將產生以下結果:

-17
-257
-4097
-65537

從正零值獲取左旋轉位整數示例

以下示例演示瞭如何使用 Integer rotateLeft() 方法透過將指定 int 值 i 的二進位制補碼錶示向左旋轉指定位數來獲取一個 int。我們建立了一個 int 變數併為其分配了一個零值。然後在 for 迴圈中使用 rotateLeft() 方法,列印生成的新整數。

package com.tutorialspoint;
public class IntegerDemo {
   public static void main(String[] args) {
      int n = 0;

      // returns the value obtained by rotating left
      for(int i = 0; i < 4; i++) {
         n = Integer.rotateLeft(n, 4);
         System.out.println(n);
      }
   }
} 

輸出

讓我們編譯並執行以上程式,這將產生以下結果:

0
0
0
0
java_lang_integer.htm
廣告