解题思路:这道题很两种解法,常规的就是O(n),另一种就是巧妙的利用位运算实现分治,时间复杂度O(1),类似于归并排序。不过这个递归不是自顶向下,而是巧用位运算从自底向上实现。
比如01001000通过这种方法得到00010010
class Solution: def reverseBits(self, n) -> int: m1 = int('10101010101010101010101010101010',2) m2 = int('11001100110011001100110011001100',2) m3 = int('11110000111100001111000011110000',2) m4 = int('11111111000000001111111100000000',2) m5 = int('11111111111111110000000000000000', 2) #自底向上 n = ((n&m1)>>1) | ((n&(m1>>1))<<1) n = ((n&m2)>>2) | ((n&(m2>>2))<<2) n = ((n&m3)>>4) | ((n&(m3>>4))<<4) n = ((n&m4)>>8) | ((n&(m4>>8))<<8) n = ((n&m5)>>16)| ((n&(m5>>16))<<16) return n