Check if the binary representation of a number is a palindrome
Problem statement
Given a number n, check if the binary representation of n is a palindrome.
Example 1:
- Input: n=5
- Output: Yes
The binary representation of 5 is 101, which is a palindrome.
Example 2:
- Input: n=10
- Output: No
The binary representation of 10 is 1010 which is not a palindrome.
Solution
The algorithm is straightforward. Find the reverse binary representation of n and compare it with the binary representation of n.
Code example
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"));}}
Code explanation
- Lines 3 to 12: We reverse the computed binary number.
- Lines 14 to 16: We compare the reverse and original binary numbers.
- Lines 19 and 20: We set a binary number and call the
isPalindrome()method.