腾讯面试题:位运算——用位存储40亿个40亿以内的整数

ε祈祈猫儿з 提交于 2020-02-02 00:54:31

一、题目

   1: #include <iostream>  
   2: using namespace std;  
   3:   
   4: typedef unsigned int Bit32;  // 能表示42亿+的无符号整数  
   5:  
   6: const Bit32 maxLen=125000001; //数组长度,0-40亿  
   7: const Bit32 thirtytwo=32;  
   8:    
   9: void createArray(Bit32 *&arr)  
  10: {  
  11:    arr=new Bit32[maxLen];  
  12:    memset(arr,(Bit32)0,sizeof(arr));  
  13: }  
  14:  
  15: bool setBit(Bit32 *arr,Bit32 num)  
  16: {  
  17:   if(((arr[num/thirtytwo])&(1<<(thirtytwo-num%thirtytwo-1)))==0)  
  18:   {  
  19:      arr[num/thirtytwo]|=1<<(thirtytwo-num%thirtytwo-1);  
  20:      return true;  
  21:   }  
  22:   else  
  23:   {  
  24:      return false;  
  25:    }  
  26: }  
  27:   
  28: int main()  
  29: {  
  30:    Bit32 *s;  
  31:    createArray(s);  
  32:    if(!setBit(s,5))  
  33:    {  
  34:        cout<<"标记失败"<<endl;  
  35:    }  
  36:    if(!setBit(s,64))  
  37:    {  
  38:        cout<<"标记失败"<<endl;  
  39:    }  
  40:    if(!setBit(s,1))  
  41:    {  
  42:        cout<<"标记失败"<<endl;  
  43:    }  
  44:  
  45:    return 0;  
  46: }  

 

二、位运算总结复习

1、2的n次方对应的十进制数字范围

位数n 2的n次方十进制数值 对应的数量级 特殊含义说明
0 1  
1 2  
2 4  
3 8  
4 16  
5 32  
6 64  
7 128  
8 256  
9 512  
10 1024  
11 2048  
12 4096  
13 8192  
14 16384  
15 32768  
16 65536  
17 131072 十万  
18 262144 十万  
19 524288 十万  
20 1048576 百万  
21 2097152 百万  
22 4194304 百万  
23 8388608 百万  
24 16777216 千万  
25 33554432 千万  
26 67108864 千万  
27 134217728 亿  
28 268435456 亿  
29 536870912 亿  
30 1073741824 十亿  
31 2147482648 十亿  
32 4294967296 十亿  
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!