首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

java-按位反转一个整数-Reverse bits of an unsigned integer

2012-09-24 
java-按位反转一个整数-Reverse bits of an unsigned integer.see http://www.leetcode.com/2011/08/rever

java-按位反转一个整数-Reverse bits of an unsigned integer.
see http://www.leetcode.com/2011/08/reverse-bits.html

public class ReverseBitsOfInteger {/** * like reversing a string. * we swap the bits in (0,N-1),(1,N-2)...... * we do it with XOR *  */public static void main(String[] args) {int y = 0x01010101;int z = reverseBits(y);//z=ox80808080System.out.printf("%x\n%x", y, z);}public static int reverseBits(int y) {// INT_SIZE=32 in generalint INT_SIZE = Integer.SIZE;for (int i = 0; i < INT_SIZE / 2; i++) {int j = INT_SIZE - 1 - i;int low = (y >> i) & 1;int high = (y >> j) & 1;int A = 1 << i;int B = 1 << j;if ((high ^ low) == 1) {y = y ^ (A | B);}}return y;}}

热点排行