如何检查整数的二进制表示是否是回文?

2022-01-09 00:00:00 binary c integer c++ palindrome

如何检查整数的二进制表示是否为回文?

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

推荐答案

由于您还没有指定要使用的语言,这里有一些 C 代码(不是最有效的实现,但它应该说明这一点):

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 已为您的 10001 事物修复.

EDIT fixed for your 10001 thing.

相关文章