天天看點

Reverse bits - 按位反轉一個int型數字

Reverse bits of a given 32 bits unsigned integer.

For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), 

return 964176192 (represented in binary as00111001011110000010100101000000).

把一個無符号int數字,按二進制位反轉過來

通過移位操作,一位一位來處理。目的是反轉,是以先處理最右位。最右位(末端)一個一個地往result的左邊推

public class ReverseBits {

   public static void main(String args[]) {
       System.out.print(solution(43261596));

   }

   // &:當兩邊操作數的位同時為1時,結果為1,否則為0。如1100&1010=1000
   // 按位反轉一個int
   private static int solution(int input) {
       int result = 0;
       for (int i = 0; i < 32; i++) {      // 一共32位
           if (((input >> i) & 1) == 1) {  // 如果移位後最右位為1
               int j = 31 - i;             // 判斷目前是第幾位,并換算成反轉後的位數
               result |= 1 << j;           // 得知是反轉後第幾位,存入結果result中
           }
       }
       return result;
   }
}      

輸出:

964176192

繼續閱讀