Java 程式,用於反轉一個正整數的各位


一個整數各位的二進位制位可以反轉來獲得另一個數字。一個例子如下所示:-

Number = 11
Binary representation = 1011
Reversed binary representation = 1101
Reversed number = 13

一個演示此過程的程式如下:-

示例

 即時演示

public class Example {
   public static void main(String[] args) {
      int num = 14;
      int n = num;
      int rev = 0;
      while (num > 0) {
         rev <<= 1;
         if ((int)(num & 1) == 1)
         rev ^= 1;
         num >>= 1;
      }
      System.out.println("The original number is: " + n);
      System.out.println("The number with reversed bits is: " + rev);
   }
}

輸出

The original number is: 14
The number with reversed bits is: 7

現在,我們來理解一下上面的程式。

定義了一個數字。然後使用一個 while 迴圈來反轉該數字的各位。用來演示此過程的程式碼片段如下:-

int num = 14;
int n = num;
int rev = 0;
while (num > 0) {
   rev <<= 1;
   if ((int)(num & 1) == 1)
   rev ^= 1;
   num >>= 1;
}

最終,顯示數字和反轉後的數字。用來演示此過程的程式碼片段如下:-

System.out.println("The original number is: " + n);
System.out.println("The number with reversed bits is: " + rev);

更新時間:2020-06-27

245 瀏覽

啟動您的 職業生涯

完成課程認證

開始
廣告