位运算——Reverse Bits
来源:互联网 发布:电视网络机顶盒多少钱 编辑:程序博客网 时间:2024/05/18 21:05
Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).
Follow up:
If this function is called many times, how would you optimize it?
JAVA代码:
方法一:依次遍历数字的二进制位,遇到第k位为1,则结果反向(32-1-k)置1
public class Solution { // you need treat n as an unsigned value public int reverseBits(int n) { int result = 0; if((n == 0) || (n == 0xffffffff )) { return n; } for(int k = 0; k < 32; k++) { if((n & 0x01) == 1) { result |= (1 << (32-k-1)); } n = n>>1; } return result; }}
法二:第二种方法是参考网上的写法:
public class Solution { // you need treat n as an unsigned value public int reverseBits(int n) { int Int_Size = Integer.SIZE; if((n == 0) || (n == 0xffffffff )) { return n; } for(int i = 0; i < Int_Size/2; i++) { int j = Int_Size-1-i; int low = (n >> i) & 1; int high = (n >> j) & 1; int a = 1 << i; int b = 1 << j; if((low ^ high) == 1) { n = n ^ (a|b); } } return n; }}
0 0
- 位运算——Reverse Bits
- (*leetcode_位运算)Reverse Bits
- LeetCode 190 Reverse Bits (位运算 推荐)
- leetcode-190 reverse bits 位运算
- Leetcode#190. Reverse Bits (反向位&位运算)
- LeetCode190—Reverse Bits
- leetcode 190. Reverse Bits-二进制翻转|位运算
- Reverse Bits-位反转
- LeetCode190——Reverse Bits
- LeetCode190——Reverse Bits
- LeetCode190——Reverse Bits
- Reverse Bits 二进制数反转 比较多的位运算符的使用
- [LeetCode]--190. Reverse Bits(不是很懂的位运算)
- 338. Counting Bits--位运算
- UVA11645 Bits【位运算+大数】
- 字节的按位逆序 Reverse Bits
- Reverse Bits(数的位倒置)
- [LeetCode-190] Reverse Bits(反转位)
- oracle分析函数:三、first,first_value,lag,lead函数
- 日常记录(二)SpringMVC导出Excel
- 在批处理模式下使用mysql
- Android下屏幕适配
- BOM
- 位运算——Reverse Bits
- IP路由及静态路由配置
- 该如何处理弹出“密码长度无效”错误
- 写linux驱动程序的步骤
- Linux进程间通信机制的一些细节
- SSM(二)Lucene全文检索
- 信息检索导论——五、索引压缩
- uboot搬移部分和重定位部分的代码分析
- Opencv显示创建Mat对象的七种方式