且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-26 08:39:52

由于您还没有指定要使用的语言,这里有一些 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.