190. Reverse Bits

来源:互联网 发布:天刀怎样导入捏脸数据 编辑:程序博客网 时间:2024/06/14 06:24

Reverse bits of a given 32 bits unsigned integer.

For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000).

Follow up:
If this function is called many times, how would you optimize it?


比较巧妙(取出每一位置的值后直接左移31~0位,然后相加)

相当于从n的低位开始取数,每次取一个数,取到的数放在新数的最低位,然后把新数左移一位,这样处理完就是反的。

public static int reverseBits(int n) {        int result = 0;        for (int i = 0; i < 32; i++) {            result += n & 1;            n >>>= 1;            if (i < 31) {                result <<= 1;            }        }        return result;    }


0 0
原创粉丝点击