Reverse Bits
2016-07-12 14:38
357 查看
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解法:
解法1:32位的整数,从最低位与最高位开始分别观察,若对应位置上异或为1,则需交换两者的位置。否则不交换;
解法2: 32位的整数,从最低位开始遍历,每位向左移位(32-i-1)位。
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解法:
解法1:32位的整数,从最低位与最高位开始分别观察,若对应位置上异或为1,则需交换两者的位置。否则不交换;
解法2: 32位的整数,从最低位开始遍历,每位向左移位(32-i-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; } }
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; } }
相关文章推荐
- 使用位运算实现网页中的过滤、筛选功能实例
- C#枚举中的位运算权限分配浅谈
- shell 基本计算、逻辑运算、位运算详解
- Java位运算和逻辑运算的区别实例
- 优秀程序员必须知道的20个位运算技巧
- 图文详解C语言位运算基础知识
- JavaScript使用位运算符判断奇数和偶数的方法
- java位运算加密示例
- c语言中用位运算实现加法技巧介绍
- 基础的十进制按位运算总结与在Python中的计算示例
- Java 位运算(移位、位与、或、异或、非)
- 位运算应用口诀和实例
- 【位运算】之 异或
- JavaScript 位运算笔记
- 想知道&&与&及||与|之间的区别吗?
- 想知道&&与&及||与|之间的区别吗?
- 不用if判断将字母进行大小写转换
- 位级运算的一点随笔
- 优秀程序员不得不知道的20个位运算技巧
- mysql位运算的应用