diff --git a/src/main/java/com/thealgorithms/bitmanipulation/ReverseBits.java b/src/main/java/com/thealgorithms/bitmanipulation/ReverseBits.java new file mode 100644 index 000000000000..58359598266e --- /dev/null +++ b/src/main/java/com/thealgorithms/bitmanipulation/ReverseBits.java @@ -0,0 +1,20 @@ +package com.thealgorithms.bitmanipulation; + +/** + * Converts any Octal Number to a Binary Number + * @author Bama Charan Chhandogi + */ + +public class ReverseBits { + + public static int reverseBits(int n) { + int result = 0; + int bitCount = 32; + for (int i = 0; i < bitCount; i++) { + result <<= 1; // Left shift the result to make space for the next bit + result |= (n & 1); // OR operation to set the least significant bit of result with the current bit of n + n >>= 1; // Right shift n to move on to the next bit + } + return result; + } +} \ No newline at end of file diff --git a/src/test/java/com/thealgorithms/bitmanipulation/ReverseBitsTest.java b/src/test/java/com/thealgorithms/bitmanipulation/ReverseBitsTest.java new file mode 100644 index 000000000000..730e345686b6 --- /dev/null +++ b/src/test/java/com/thealgorithms/bitmanipulation/ReverseBitsTest.java @@ -0,0 +1,15 @@ +package com.thealgorithms.bitmanipulation; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +class ReverseBitsTest { + + @Test + void testReverseBits() { + assertEquals(0, ReverseBits.reverseBits(0)); + assertEquals(-1, ReverseBits.reverseBits(-1)); + assertEquals(964176192, ReverseBits.reverseBits(43261596)); + } +}