位運算(3)——Reverse Bits

翻轉32位無符號二進制整數this

Reverse bits of a given 32 bits unsigned integer.spa

For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).code

Follow up:
If this function is called many times, how would you optimize it?blog

 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 }

另外一種寫法:input

 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。it

相關文章
相關標籤/搜索