[英]How to check if number is bit palindrome or not
我必須編寫一個代碼來檢查數字是否是位回文。 例如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;
}
下面的實現將在O(n / 2)中執行,其中n是給定數字的位長:
#define LSB(bit_len) 0x1
#define MSB(bit_len) 0x1 << bit_len - 1
int isBitPalindrome(int x) {
int i = 0, bit_len = sizeof(int) * 8;
unsigned int left = 0, right = 0;
while (i < bit_len / 2) {
left = x << i & MSB(bit_len);
right = x >> i & LSB(bit_len);
if ((left == 0x0 && right == 0x0) ||
(left == MSB(bit_len) && right == LSB(bit_len))
i++;
else
break;
}
return (i == bit_len / 2) ? 1 : 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.