How to check if the binary representation of an integer is a palindrome?

23,232

Solution 1

Since you haven't specified a language in which to do it, here's some C code (not the most efficient implementation, but it should illustrate the point):

/* flip n */
unsigned int flip(unsigned int n)
{
    int i, newInt = 0;
    for (i=0; i<WORDSIZE; ++i)
    {
        newInt += (n & 0x0001);
        newInt <<= 1;
        n >>= 1;
    }
    return newInt;
}

bool isPalindrome(int n)
{
    int flipped = flip(n);
    /* shift to remove trailing zeroes */
    while (!(flipped & 0x0001))
        flipped >>= 1;
    return n == flipped;
}

EDIT fixed for your 10001 thing.

Solution 2

Hopefully correct:

_Bool is_palindrome(unsigned n)
{
    unsigned m = 0;

    for(unsigned tmp = n; tmp; tmp >>= 1)
        m = (m << 1) | (tmp & 1);

    return m == n;
}

Solution 3

Create a 256 lines chart containing a char and it's bit reversed char. given a 4 byte integer, take the first char, look it on the chart, compare the answer to the last char of the integer. if they differ it is not palindrome, if the are the same repeat with the middle chars. if they differ it is not palindrome else it is.

Solution 4

Plenty of nice solutions here. Let me add one that is not the most efficient, but very readable, in my opinion:

/* Reverses the digits of num assuming the given base. */
uint64_t
reverse_base(uint64_t num, uint8_t base)
{
  uint64_t rev = num % base;

  for (; num /= base; rev = rev * base + num % base);

  return rev;
}

/* Tells whether num is palindrome in the given base. */
bool
is_palindrome_base(uint64_t num, uint8_t base)
{
  /* A palindrome is equal to its reverse. */
  return num == reverse_base(num, base);
}

/* Tells whether num is a binary palindrome. */ 
bool
is_palindrome_bin(uint64_t num) 
{
  /* A binary palindrome is a palindrome in base 2. */
  return is_palindrome_base(num, 2);
}

Solution 5

The following should be adaptable to any unsigned type. (Bit operations on signed types tend to be fraught with problems.)

bool test_pal(unsigned n)
{
  unsigned t = 0;

  for(unsigned bit = 1; bit && bit <= n; bit <<= 1)
    t = (t << 1) | !!(n & bit);

  return t == n;
}
Share:
23,232
yesraaj
Author by

yesraaj

Learning c++,Check out my blog

Updated on July 21, 2022

Comments

  • yesraaj
    yesraaj almost 2 years

    How to check if the binary representation of an integer is a palindrome?