美文网首页
Leetcode 190 - Reverse Bits

Leetcode 190 - Reverse Bits

作者: BlueSkyBlue | 来源:发表于2018-07-21 12:29 被阅读4次

题目:

Reverse bits of a given 32 bits unsigned integer.
Example:

Input:43261596
Output:964176192
Explanation: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?


思路:

该题是一道与二进制位运算有关的题目。首先将给定数字n的第一位的数字取出将其向左移动31位。再取第二位数字,向左移动30位,依次类推。


代码:

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

相关文章

网友评论

      本文标题:Leetcode 190 - Reverse Bits

      本文链接:https://www.haomeiwen.com/subject/jwkhmftx.html