TypechoJoeTheme

IT技术分享

统计

[LeetCode 190] Reverse Bits [Java] [Runtime : 3MS]

2017-08-31
/
0 评论
/
664 阅读
/
正在检测是否收录...
08/31

1. Description

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?

2. Runtime Distribution

3. Submission Details

4. Example

Input: 43261596
Ouput: 964176192

5. Code

public int reverseBits(int n) {
    for (int i = 0; i < 16; i++) {
        int lowBit = (n >> i) & 1;
        int highBit = (n >> (31 - i)) & 1;
        if ((lowBit ^ highBit) == 1) {
            n ^= (1 << i) | (1 << 31 - i);
        }
    }
    return n;
}

6.Test

public class LeetCode0190 {
    public int reverseBits(int n) {
        for (int i = 0; i < 16; i++) {
            int lowBit = (n >> i) & 1;
            int highBit = (n >> (31 - i)) & 1;
            if ((lowBit ^ highBit) == 1) {
                n ^= (1 << i) | (1 << 31 - i);
            }
        }
        return n;
    }

    public static void main(String[] args) {
        LeetCode0190 leetcode = new LeetCode0190();
        System.out.println(leetcode.reverseBits(43261596));
    }
}
BIT
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/763/(转载时请注明本文出处及文章链接)