📜  使用O(1)时间中的查找表反转位

📅  最后修改于: 2021-05-25 04:49:56             🧑  作者: Mango

给定一个无符号整数,将其所有位取反,然后用相反的位返回数字。

例子:

Input : n = 1
Output : 2147483648  
On a machine with size of unsigned
bit as 32. Reverse of 0....001 is
100....0.

Input : n = 2147483648
Output : 1       

在上一篇文章中,我们看到了两种在O(n)和O(logn)时间内解决此问题的方法。在这里,我们使用查找表在O(1)时间内解决了这个问题。使用查找表一次性很难将所有32位(假定为int的大小)反转(“,因为创建大小为2 32 -1”的查找表是不可行的)。因此,我们将32位分解为8位块(大小为2 8 -1“ 0-255”的查找表)。

查找表
在查询故事中,我们将存储范围在(0-255)中的每个数字的倒数

LookupTable [0] = 0 |二进制00000000反向00000000
LookupTable [1] = 128 |二进制00000001反向10000000
LookupTable [2] = 64 |二进制00000010反向01000000
LookupTanle [3] = 192 |二进制00000011反向11000000
LookupTable [4] = 32 |二进制00000100反向00100000
依此类推……直至lookuptable [255]。

让我们举个例子,查找表是如何工作的。
设号码= 12456
二进制= 00000000000000000011000010101000

Split it into 8 bits chunks  :  00000000 | 00000000 | 00110000 | 10101000
         in decimal          :     0          0          48       168
reverse each chunks using lookup table :
Lookuptable[ 0 ] = 0  | in binary 00000000
Lookuptable[48 ] = 12 | in binary 00001100
Lookuptable[168] = 21 | in binary 00010101
 
Now Binary :  
00000000 | 00000000 | 00001100 | 00010101

Binary chunks after rearrangement : 
00010101 | 00001100 | 00000000 | 00000000   
  
Reverse of 12456 is 353107968  
// CPP program to reverse bits using lookup table.
#include
using namespace std;
   
// Generate a lookup table for 32bit operating system 
// using macro 
#define R2(n)     n,     n + 2*64,     n + 1*64,     n + 3*64
#define R4(n) R2(n), R2(n + 2*16), R2(n + 1*16), R2(n + 3*16)
#define R6(n) R4(n), R4(n + 2*4 ), R4(n + 1*4 ), R4(n + 3*4 )
  
// Lookup table that store the reverse of each table
unsigned int lookuptable[256] = { R6(0), R6(2), R6(1), R6(3) };
  
/* Function to reverse bits of num */
int reverseBits(unsigned int num)
{
    int reverse_num = 0;
  
     // Reverse and then rearrange 
  
                   // first chunk of 8 bits from right
     reverse_num = lookuptable[ num & 0xff ]<<24 | 
  
                   // second chunk of 8 bits from  right 
                   lookuptable[ (num >> 8) & 0xff ]<<16 | 
  
                   lookuptable[ (num >> 16 )& 0xff ]<< 8 |
                   lookuptable[ (num >>24 ) & 0xff ] ;
    
    return reverse_num;
}
  
//driver program to test above function 
int main()
{
    int x = 12456; 
    printf("%u", reverseBits(x));    
    return 0;
} 

输出:

353107968

时间复杂度:O(1)