Cómo verificar si el número es palíndromo de bits o no
Frecuentes
Visto 12,871 veces
6
I have to write a code to check if the number is bit palindrome. e.g. 9(1001) is bit palindrome but 6(110) is not a bit palindrome.
I have written the code to convert the number into a string which represents that numbers in binary and then checked for string palindrome. Is there any better way to do this?
2 Respuestas
22
We can do this using bit wise operators. The idea is to read each bit, one at a time, of the number from right to left and generate another number using these bits from left to right. Finally, we compare these two numbers. If they are same, the original number is a binary bit palindrome.
int isBitPalindrome(int x) {
int reversed = 0, aux = x;
while (aux > 0) {
/*
Before doing that shifting reversed to
right, to build it from left to right.
Takes LSB of aux and puts it as LSB of reversed
variable.
*/
reversed = (reversed << 1) | (aux & 1);
/*
Loop depends on number of bits in aux. Takes next bit into
LSB position by shifting aux right once.
*/
aux = aux >> 1;
}
return (reversed == x) ? 1 : 0;
}
Respondido el 29 de junio de 16 a las 19:06
0
Below implementation will execute in O(n/2), where n is bit length of given number:
#define LSB(bit_len) 0x1
#define MSB(bit_len) 0x1 << bit_len - 1
int isBitPalindrome(int x) {
int i = 0, bit_len = sizeof(int) * 8;
unsigned int left = 0, right = 0;
while (i < bit_len / 2) {
left = x << i & MSB(bit_len);
right = x >> i & LSB(bit_len);
if ((left == 0x0 && right == 0x0) ||
(left == MSB(bit_len) && right == LSB(bit_len))
i++;
else
break;
}
return (i == bit_len / 2) ? 1 : 0;
}
Respondido el 13 de Septiembre de 18 a las 09:09
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas c bit-manipulation or haz tu propia pregunta.
The approach sounds good, but the code has poor clarity. Why no meaningful variable-names? Good variable-names would be
x
,reversed
yremain
. And why the logical -> int for the return? Try to write code that's near readable English, use comments to explain more-complex bits (like buildingy
). - Tomas W.@ThomasW Thanks for the suggestings. I have made those changes in my code. - Patada de Vallabh
Great! Good approach to the logic. - Tomas W.