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?
思路
基本思路即分别提取出当前最高位和最低位的信息,进行交换即可,然后最高位置--,最低位位置++,直到相遇;32位数,所以0-15和16-31分别进行操作。这边我先判断最高位,如果为1,则判断最低位,如果也为1,不进行操作,如果为0,则最低为变成1,这边用到了位移,然后最高位做减法,则变为0。如果最高位为0,同理,做相反的操作即可。
class Solution { public: uint32_t reverseBits(uint32_t n) { int cur; for(int i = 31 ; i >= 16;i--){ if(n&(1<<i)){ cur = n&1<<(31-i); if(cur == 0){ n -= 1<<i; n += 1<<(31-i); } } else{ cur = n&1<<(31-i); if(cur != 0){ n += 1<<i; n -=1<<(31-i); } } } return n; } };