每天一道LeetCode >> 翻转一个数的比特位(java)

题目:Reverse bits of a given 32 bits unsigned integer.
java需要注意的是:

(1)Note that in some languages such as Java, there is no unsigned integer type. In this case, both input and output will be given as signed integer type and should not affect your implementation, as the internal binary representation of the integer is the same whether it is signed or unsigned.
(2)In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 2 above the input represents the signed integer -3 and the output represents the signed integer -1073741825.
  • 一个整型有4个字节,每个字节八个比特位(一个Byte),将整型进行分解分别对每个Byte进行翻转,再合并就可以实现对原数字比特位的翻转。
        for (int i = 0; i < 4; i++) {
			ret <<= 8;
			ret |= reverseByte((byte) (n & 0b11111111));
			n >>= 8;
		}

如上所示,其中(n & 0b11111111)是为了截取转换成整型的后八位,0b代表后面的数字是二进制,和n相与之后会自动转换为整型,如果不对后八位进行截取,那么前面的24位会补1会造成结果的错误。前面的Byte是为了类型转换。

完整的代码实现:

	public static void main(String[] args) {
		int n = 43261596;
		System.out.println(reverseBits(n));
	}
	private static Map<Byte, Integer> cache = new HashMap<>();

	public static int reverseBits(int n) {
		int ret = 0;
		for (int i = 0; i < 4; i++) {
			ret <<= 8;
			ret |= reverseByte((byte) (n & 0b11111111));
			n >>= 8;
		}
		return ret;
	}

	private static int reverseByte(byte b) {
		if (cache.containsKey(b))
			return cache.get(b);
		int ret = 0;
		byte t = b;
		for (int i = 0; i < 8; i++) {
			ret <<= 1;
			ret |= t & 1;
			t >>= 1;
		}
		cache.put(b, ret);
		return ret;
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值