欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Reverse Bits

程序员文章站 2022-05-02 19:09:21
...
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).

给定一个无符号的整数,将它的每个比特位都逆转,返回逆转之后新的数。通过位运算,取32个不同位上的数字,同时通过左移来得到结果。代码如下:
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++) {
            result <<= 1;
            result |= (n >> i & 1);
        }
        return result;
    }
}
相关标签: 位运算

上一篇: Number of 1 Bits

下一篇: Single Number III