Given a number n
, check if the binary representation of n
is a palindrome.
Example 1:
The binary representation of 5
is 101
, which is a palindrome.
Example 2:
The binary representation of 10
is 1010
which is not a palindrome.
The algorithm is straightforward. Find the reverse binary representation of n
and compare it with the binary representation of n
.
Let’s look at the code below:
class Main{public static int findReverse(int n){int reverse_bin = 0;int temp = n;while (temp > 0) {reverse_bin = (reverse_bin << 1) | (temp & 1);temp = temp >> 1;}return reverse_bin;}public static boolean isPalindrome(int n) {return n == findReverse(n);}public static void main(String[] args) {int n = 10;System.out.println("Is binary representation of " + n + " a palindraome? " + (isPalindrome(n)?"Yes":"No"));}}
isPalindrome()
method.