LeetCode 190 Reverse Bits

来源:互联网 发布:淘宝售假扣24分怎么办 编辑:程序博客网 时间:2024/06/05 02:58

LeetCode 190 Reverse Bits

问题来源LeetCode190 Reverse Bits

问题描述

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?

Related problem: Reverse Integer

问题分析

这道题是将无符号整形的二进制进行反转。这里需要注意无符号整形这个问题。Java里面没有无符号的概念,所以需要转化为Long,然后进行操作。最后又涉及到如何把Long转化成对应的Int二进制。也就是要处理一下符号位。

代码分析

// you need treat n as an unsigned valuepublic int reverseBits(int n) {  long unsignedN = n&0x0FFFFFFFFl;    unsignedN |=0x100000000l;    long res = 0;    while (unsignedN!=1){        res |= unsignedN&1;        res<<=1;        unsignedN>>=1;    }    res>>=1;    if((res&0x080000000l)==0x080000000l){        return (int)res|0b1000_0000_0000_0000_0000_0000_0000_0000;    }else return (int)res;}

LeetCode学习笔记持续更新

GitHub地址 https://github.com/yanqinghe/leetcode

CSDN博客地址 http://blog.csdn.net/yanqinghe123/article/category/7176678