位运算(3)——Reverse Bits

翻转32位无符号二进制整数

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 public class Solution {
 2     // you need treat n as an unsigned value
 3     public int reverseBits(int n) {
 4         int res = 0;
 5         for(int i=0; i<32; i++) {
 6             res = res + (n & 1);
 7             if(i < 31) {
 8                 res = res << 1;
 9             }
10             n = n >> 1;
11         }
12         return res;
13     }
14 }

另一种写法:

 1   public int reverseBits(int n) {
 2         int res = 0;
 3         for(int i=0; i<32; i++) {
 4             if((n & 1) == 1) {
 5                 res = (res << 1) + 1;
 6             } else {
 7                 res = res << 1;
 8             }
 9             n = n >> 1;
10         }
11         return res;
12     }

思路都是从右到左判断0/1,加到res。

posted @ 2017-05-25 15:18  D-Dong  阅读(364)  评论(0编辑  收藏  举报