Skip to content

Commit

Permalink
BitManipulationTest - reverseBits
Browse files Browse the repository at this point in the history
  • Loading branch information
bky373 committed Jun 3, 2024
1 parent 493a9db commit 9e2baff
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/test/java/BitManipulationTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import org.junit.jupiter.api.Test;

public class BitManipulationTest {

/**
* https://leetcode.com/problems/reverse-bits/
*/
@Test
void reverseBits() {
int n = Integer.parseInt("00000010100101000001111010011100", 2);
System.out.println("n = " + n);
System.out.println("Integer.toBinaryString(n) = " + Integer.toBinaryString(n));
int ans = 0;

// Loop through each bit of the integer (32 bits for an int)
for (int i = 0; i < 32; i++) {
// Shift `ans` left by 1 (equivalent to multiplying by 2) and OR with the rightmost bit of `n`
ans = ans << 1 | n & 1;

// Shift `n` right by 1 to process the next bit
n >>= 1;
}
System.out.println("ans = " + ans);
System.out.println("Integer.toBinaryString(ans) = " + Integer.toBinaryString(ans));
}
}

0 comments on commit 9e2baff

Please sign in to comment.