---
title: "Reverse Bits"
author: "KickCode"
date: "2016-02-17T04:00:59Z"
tags: []
categories: ["编程语言"]
slug: "reverse-bits"
draft: false
lastmod: "2016-02-17T04:00:59Z"
id: 2276833
url: "https://kickcode.iteye.com/blog/2276833"
---

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个不同位上的数字，同时通过左移来得到结果。代码如下：

```java

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;
    }
}

```