腾讯面试题:位运算——用位存储40亿个40亿以内的整数
一、题目
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 | 十亿 |

浙公网安备 33010602011771号