190. Reverse Bits

来源:互联网 发布:逆波兰表达式算法 java 编辑:程序博客网 时间:2024/06/05 06:45

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

思路:
将32位的无符号整数n右移32次,每次移动取出最低位,赋值给另一个变量result, 对应于n的右移,result对应地左移32次。(result需要先右移,再将n的最低位赋值给result,否则当输入n=2147483648时,会溢出,因为java的int类型是有符号的,能表示的最大的数是2147483647)。

public class Solution {    // you need treat n as an unsigned value    public int reverseBits(int n) {        int result = 0;        for (int i=0; i<32; i++){            // 取出n的最低位            int least = n & 0x01;            // n右移一位            n = n >> 1;            // 下面两个步骤需要注意:一定要先左移,再赋值。            // 否则当n=2147483648时,result = result | least 会溢出。            // 将result左移一位            result = result << 1;            // 将n的最低位加到result最后一位            result = result | least;        }        return result;    }}
原创粉丝点击