Reverse bits of an unsigned integer
来源:互联网 发布:如何查询淘宝旺旺号 编辑:程序博客网 时间:2024/06/04 18:42
1.将原无符号从低到高按比特取出构造出它的反转
typedef unsigned int uint;uint reverseBits2(uint x){ uint i,y=0; for(i = 0;i < 32;i++){ y <<= 1; y |= (x & 1); // x >>= 1; } return y;}
2.利用异或操作
逆置一个无符号数的比特序列可以通过将对称的n/2bits进行交换,swapBits(i,j)交换第i和第j个bit,如果二者不同的话,判断2个比特是否相同也是使用XOR操作,而且0,1和1进行异或即可得到对应的反码。时间复杂度仍然是O(n),n是比特数。
uint swapBits(uint x, uint i, uint j){ uint left = (x >> i) & 1; uint right = (x >> j) & 1; if(left ^ right) x ^= (1U << i) | (1U << j); return x;}uint reverseBits(uint x){ uint i; uint n = sizeof(x) * 8; for(i = 0;i < n/2;i++) x = swapBits(x,i,n-i-1); return x;}
3.分治法
先是奇数位和偶位数交换,然后奇数对和偶数对,而后是triple,等等,类似于归并排序,经过logN步的重构就会得到反转后的结果。拿8bits来说,&0x55,&0xAA可以分别得到奇数位和偶数位(mask其它的位),而后奇数位左移一个单位,偶数位后移一位,逻辑加就可以实现相邻奇偶的对置;&0x33,&0xCC可以分别得到奇数对和偶数对,而后分别左移,后移一个单位(这里的标量变成了2 bits),逻辑加更新。。。。其实整个操作就是选取合适的掩码,从最小粒度开始,逐步回归到最终的结果。
//here is special 4B , so need 5 stepsuint reverseBits3(uint x){ assert(sizeof(x) == 4); x = ((x & 0x55555555) << 1) | ((x & 0xAAAAAAAA) >> 1); x = ((x & 0x03030303) << 2) | ((x & 0xCCCCCCCC) >> 2); x = ((x & 0x0F0F0F0F) << 4) | ((x & 0xF0F0F0F0) >> 4); x = ((x & 0x00FF00FF) << 8) | ((x & 0xFF00FF00) >> 8); x = ((x & 0x0000FFFF) << 16) | ((x & 0xFFFF0000) >> 16); return x;}
0 0
- Reverse bits of an unsigned integer
- Reverse bits of a given 32 bits unsigned integer
- Reverse digits of an integer.
- reverse digits of an integer.
- Reverse digits of an integer.
- Reverse digits of an integer.
- Reverse digits of an integer.
- reverse digits of an integer
- Reverse digits of an integer.
- leetcode 75: Reverse digits of an integer.
- 【LeetCode】Reverse digits of an integer
- leetcode:Reverse digits of an integer
- LeetCode Reverse digits of an integer.
- leetcode Reverse digits of an integer
- leetcode 7 Reverse digits of an integer
- Problem 7.Reverse digits of an integer.
- leetcode-T7 Reverse digits of an integer
- Reverse digits of an integer(数字倒换)
- 在sqlplus里用sys用户登录oracle
- sql 截取
- android 中数据库 用SQLiteOpenHelper建立后就不会再oncreat
- 数据分析资源汇总(持续更新中)
- 由std::string继承引起的LNK 2005错误
- Reverse bits of an unsigned integer
- 将数组中所有小于或等于0的元素都放在数组前面,大于0的元素放在数组后面
- asp.net @ 指令
- jw player学习笔记----跨域请求
- powerfull makefile
- JSON静态分页
- Memory Translation and Segmentation
- mysql 添加、删除、修改字段
- 设计模式(一)