Reverse Bits

描述

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?

分析

最简单直接的做法,从右向左把一位位取出来,添加到新生成的整数的最低位即可。

第二个简单的方法,左右不断交换位,直到相遇。

解法1

  1. // Reverse Bits
  2. // Time Complexity: O(logn), Space Complexity: O(1)
  3. public class Solution {
  4. // you need treat n as an unsigned value
  5. public int reverseBits(int n) {
  6. int result = 0;
  7. for (int i = 0; i < 32; ++i) {
  8. if ((n & 1) == 1) {
  9. result = (result << 1) + 1;
  10. } else {
  11. result = result << 1;
  12. }
  13. n = n >> 1;
  14. }
  15. return result;
  16. }
  17. }

解法2

  1. // Reverse Bits
  2. // Time Complexity: O(logn), Space Complexity: O(1)
  3. public class Solution {
  4. // you need treat n as an unsigned value
  5. public int reverseBits(int n) {
  6. int left = 0;
  7. int right = 31;
  8. while (left < right) {
  9. // swap bit
  10. int x = (n >> left) & 1;
  11. int y = (n >> right) & 1;
  12. if (x != y) {
  13. n ^= (1 << left) | (1 << right);
  14. }
  15. ++left;
  16. --right;
  17. }
  18. return n;
  19. }
  20. }

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/bitwise-operations/reverse-bits.html