Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000).
Follow up:
If this function is called many times, how would you optimize it?
首先,自己定一个比较小的数分析,比如a=10100,反转成b=00101;
那么,想到通过位运算。a右移,移出的最右边的那一位要放在b中左移,那么一步步进行下来,b就是a的反转;
编程时注意逻辑顺序,第一次我就把b的先左移,后加考虑反了(这也是初始时候的边界检测),下面是代码:
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
int rn, tmp = 0;
for(int i=0; i<32; i++)
{
rn <<= 1;
rn += (n & 0x01);
n >>= 1;
// combined by rn = (rn << 1) + (n>>i & 1);
}
return rn;
}
};
二进制运算的还有很多,比如:“一串数只有1个出现一次,其余都出现两次,找出这个数;”,“一串数有2个出现1次,其他都出现两次,找出这两个数”;
这些都借鉴了异或运算的特点。