如何检查整数的二进制表示是否是回文? [英] How to check if the binary representation of an integer is a palindrome?

查看:34
本文介绍了如何检查整数的二进制表示是否是回文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于如何检查整数的二进制表示是否是回文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆