Skip to content

Commit f3fd7e6

Browse files
committed
feat: Add BinaryPalindromeCheck new algorithm with Junit tests
1 parent 90d20b3 commit f3fd7e6

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package com.thealgorithms.bitmanipulation;
2+
3+
/**
4+
* This class contains a method to check if the binary representation of a number is a palindrome.
5+
* <p>
6+
* A binary palindrome is a number whose binary representation is the same when read from left to right and right to left.
7+
* For example, the number 9 has a binary representation of 1001, which is a palindrome.
8+
* The number 10 has a binary representation of 1010, which is not a palindrome.
9+
* </p>
10+
*
11+
* @author Hardvan
12+
*/
13+
public final class BinaryPalindromeCheck {
14+
private BinaryPalindromeCheck() {
15+
}
16+
17+
/**
18+
* Checks if the binary representation of a number is a palindrome.
19+
*
20+
* @param x The number to check.
21+
* @return True if the binary representation is a palindrome, otherwise false.
22+
*/
23+
public static boolean isBinaryPalindrome(int x) {
24+
int reversed = reverseBits(x);
25+
return x == reversed;
26+
}
27+
28+
/**
29+
* Helper function to reverse all the bits of an integer.
30+
*
31+
* @param x The number to reverse the bits of.
32+
* @return The number with reversed bits.
33+
*/
34+
private static int reverseBits(int x) {
35+
int result = 0;
36+
while (x > 0) {
37+
result <<= 1;
38+
result |= (x & 1);
39+
x >>= 1;
40+
}
41+
return result;
42+
}
43+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.thealgorithms.bitmanipulation;
2+
3+
import static org.junit.jupiter.api.Assertions.assertFalse;
4+
import static org.junit.jupiter.api.Assertions.assertTrue;
5+
6+
import org.junit.jupiter.api.Test;
7+
8+
public class BinaryPalindromeCheckTest {
9+
10+
@Test
11+
public void testIsBinaryPalindrome() {
12+
assertTrue(BinaryPalindromeCheck.isBinaryPalindrome(9)); // 1001 is a palindrome
13+
assertFalse(BinaryPalindromeCheck.isBinaryPalindrome(10)); // 1010 is not a palindrome
14+
assertTrue(BinaryPalindromeCheck.isBinaryPalindrome(0)); // 0 is a palindrome
15+
assertTrue(BinaryPalindromeCheck.isBinaryPalindrome(1)); // 1 is a palindrome
16+
assertFalse(BinaryPalindromeCheck.isBinaryPalindrome(12)); // 1100 is not a palindrome
17+
}
18+
}

0 commit comments

Comments
 (0)