Post

[Java] Reverse Bits

[Java] Reverse Bits

Feel free to leave a comment or contact me if you spot any errors or have feedback. I’m always open to learning!

[Java] Reverse Bits

LeetCode Problem #190 🔗 LeetCode Link

Espeically, this problem is in the Must-do List for Interview Prep in Leetcode.

Description

Reverse bits of a given 32 bits signed integer.

Example

  • Input: n = 43261596
  • Output: n = 43261596
  • Explanation:
IntegerBinary
432615960000001010010101000001111010011100
9641761920011100101011110000010100101000000

My Solution

My first apporach was using StringBuilder. But this code couldn’t pass the test.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
    public int reverseBits(int n) {
        // n is even
        StringBuilder binary = new StringBuilder(32);
        binary.append(Integer.toBinaryString(n));

        binary.reverse();

        for (int i = 0; i < 32 - binary.length(); ++i) {
            System.out.println("add 0");
            binary.append("0");
        }

        return Integer.parseInt(binary.toString(), 2);
    }
}
This post is licensed under CC BY 4.0 by the author.