我必须写一个代码来检查数字是否是位回文。例如9(1001)有点回文但6(110)不是有点回文。
我已经编写了将数字转换为以二进制表示该数字的字符串的代码,然后检查字符串回文。有没有更好的方法来做到这一点?
最佳答案
我们可以使用位运算符来做到这一点。这个想法是从右到左读取数字的每一位,一次一个,并使用这些位从左到右生成另一个数字。最后,我们比较这两个数字。 如果相同,则原数为二进制位回文数。
int isBitPalindrome(int x) {
int reversed = 0, aux = x;
while (aux > 0) {
/*
Before doing that shifting reversed to
right, to build it from left to right.
Takes LSB of aux and puts it as LSB of reversed
variable.
*/
reversed = (reversed << 1) | (aux & 1);
/*
Loop depends on number of bits in aux. Takes next bit into
LSB position by shifting aux right once.
*/
aux = aux >> 1;
}
return (reversed == x) ? 1 : 0;
}
关于c - 如何检查数字是否是位回文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18940140/