反轉二制

原題

  Reverse bits of a given 32 bits unsigned integer.
  For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).
  Follow up:
  If this function is called many times, how would you optimize it?算法

題目大意

  反轉一個32位無符號的整數。this

解題思路

  設這個數爲k,用一個初值爲0的數r保存反轉後的結果,用1對k進行求與,其結果與r進行相加,再對k向右進行一位移位,對r向左進行一位移位。值到k的最後一位處理完。spa

代碼實現

算法實現類.net

public class Solution {

    public int reverseBits(int n) {

        int result = 0;
        for (int i = 0; i < 32; i++) {
            result += n & 1;
            n >>>= 1;
            if (i < 31) {
                result <<= 1;
            }
        }
        return result;
    }
}
相關文章
相關標籤/搜索