Given a positive integer, determine if its binary (bit) representation is a palindrome. For example, 5 is a palindrome because 5 = 101. Also, 9 is a palindrome because 9 = 1001.
funisPalindromeBits(n: Int): Boolean {
if (n < 0) returnfalsevar rev = 0var num = n
while (num > 0) {
rev = (rev shl 1) or (num and 1)
num = num shr 1 }
return rev == n
}
1
2
3
4
5
6
7
8
9
10
pubfnis_palindrome_bits(n: i32) -> bool {
if n <0 { returnfalse; }
letmut rev =0;
letmut num = n;
while num >0 {
rev = (rev <<1) | (num &1);
num >>=1;
}
rev == n
}
defis_palindrome_bits_twoptr(n):
if n <0:
returnFalse left = n.bit_length() -1 right =0while left > right:
if ((n >> left) &1) != ((n >> right) &1):
returnFalse left -=1 right +=1returnTrue
publicstaticbooleanisPalindrome(int input){
if ( input < 0)
returnfalse;
int inputCopy = input;
int resultantNumber = 0;
//reverse the bits in the numberwhile (inputCopy > 0){
resultantNumber <<= 1;
if ((inputCopy & 1)!=0) {
resultantNumber |=1;
}
inputCopy >>= 1;
}
if (input == resultantNumber)
returntrue;
returnfalse;
}
In the program, we first check for invalid inputs.
resultantNumber is the number whose bit representation is the reverse of the input number. inputCopy is the copy of the input number. Since we’ll destroy the value in the process, we must make copy of it so that we can compare the result to the original input later on. We first reverse the number and then compare them to be equal.