Saturday, October 31, 2015

if binary representation of a given number is pallindrom or not

/*  test if binary representation of a given number is pallindrom */

#include<stdio.h>
#include <stdbool.h>
bool isBinPallindrom(unsigned int num) {
    if (num == 0)
       return true;
    int posL = 1;
    int posR = 1;
    int temp = num;
    while(temp>>1) {
        temp >>=1;
        posR++;
    }
    printf("num is %d, MSB pos %d\n", num, posR);
    while (posR > posL) {
        if (((num & (1 << (posR -1))) >> (posR -1)) != ((num & (1 << (posL -1))) >> (posL -1))) {
              printf ("not pallindrom\n");
              return false;
        }
        posL++;
        posR--;
    }
    return true;
}
int main()
{
    unsigned int x = 22;
    printf("The number %d is %s\n", x, isBinPallindrom(x) ? "pallindrom": "not pallindrom");
    x = 0xFF;
    printf("The number %d is %s\n", x, isBinPallindrom(x) ? "pallindrom": "not pallindrom");
    return 0;
}

No comments:

Post a Comment