176.Reverse Bits
题目:
Reverse bits of a given 32 bits unsigned integer.
给定32位无符号整数的反转位。
Example:
Input: 43261596 Output: 964176192 Explanation: 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 if((n&1)==1) 7 res=(res<<1)+1; 8 else 9 res=res<<1; 10 n=n>>1; 11 } 12 return res; 13 } 14 }
优化:
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<<=1; 7 if((n&1)==1) res++; 8 n=n>>1; 9 } 10 return res; 11 } 12 }
详解: