Skip to content

Commit 2511570

Browse files
BamaCharanChhandogiBamaCharanChhandogi
and
BamaCharanChhandogi
authored
Add Reverse Bits Algo in Bit-Manipulation (TheAlgorithms#4299)
Co-authored-by: BamaCharanChhandogi <b.c.chhandogi@gmailcom>
1 parent 07945c7 commit 2511570

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.thealgorithms.bitmanipulation;
2+
3+
/**
4+
* Converts any Octal Number to a Binary Number
5+
* @author Bama Charan Chhandogi
6+
*/
7+
8+
public class ReverseBits {
9+
10+
public static int reverseBits(int n) {
11+
int result = 0;
12+
int bitCount = 32;
13+
for (int i = 0; i < bitCount; i++) {
14+
result <<= 1; // Left shift the result to make space for the next bit
15+
result |= (n & 1); // OR operation to set the least significant bit of result with the current bit of n
16+
n >>= 1; // Right shift n to move on to the next bit
17+
}
18+
return result;
19+
}
20+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.thealgorithms.bitmanipulation;
2+
3+
import static org.junit.jupiter.api.Assertions.*;
4+
5+
import org.junit.jupiter.api.Test;
6+
7+
class ReverseBitsTest {
8+
9+
@Test
10+
void testReverseBits() {
11+
assertEquals(0, ReverseBits.reverseBits(0));
12+
assertEquals(-1, ReverseBits.reverseBits(-1));
13+
assertEquals(964176192, ReverseBits.reverseBits(43261596));
14+
}
15+
}

0 commit comments

Comments
 (0)