我必须编写代码来检查数字是否为回文。例如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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句