交換位元組中的每兩位


在本文中,我們將討論交換給定數字中每個交替位的程式碼解決方案,並返回結果數字。我們將使用位操作的概念,以便在恆定時間內解決問題,而無需使用任何迴圈。

問題陳述 - 我們得到一個數字n,我們必須交換彼此相鄰的位元對。

換句話說,我們必須將每個奇數位的位元與其相鄰的偶數位的位元交換。

約束:解決問題時,我們必須記住,我們不能為此問題使用迴圈,我們必須僅在O(1)時間複雜度內執行我們的程式碼。

示例

輸入 - n = 10011110

輸出 - 交換偶數位置的位元與奇數位置的位元後,

獲得的二進位制數為:01101101

輸入 - n = 10011110

輸出 - 交換偶數位置的位元與奇數位置的位元後,

獲得的二進位制數為:01101101

解釋 -

讓我們考慮前面的示例以更好地理解。

n = 10011110
Even position bits in n are E – 1 x 0 x 1 x 1 x
Odd position bits in n are O – x 0 x 1 x 1 x 0

對於結果,我們希望偶數位置的位元在奇數位置,反之亦然。

對於偶數位置的位元在奇數位置,

我們需要將偶數位置右移一位。

因此,對於偶數位置的位元,我們只需執行 E >> 1 以獲得所需的位置。

類似地,我們必須將奇數位置的位元左移一位以獲得奇數位元的所需位置。

因此,對於奇數位置的位元,我們只需執行 O << 1 以獲得所需的位置。

現在下一個問題是如何提取奇數和偶數位置的位元。

眾所周知,

0x55 = 01010101 in which every only odd position bits are set ( non 0 ).
0xAA = 10101010 in position bits are set. which, only odd

因此,要從n中提取E,我們只需要執行

E = n & 0xAA

類似地,要從n中提取O,我們需要執行 -

O = n & 0x55

現在,要找到交換後的輸出,

步驟

所涉及的步驟為 -

  • E >> 1

  • O << 1

  • 現在,我們使用或運算組合E和O。

  • 因此,我們的結果將是 – 結果 = (E >> 1 | O << 1)

示例

下面給出了此方法的程式碼表示 -

#include<bits/stdc++.h>
using namespace std;
unsigned int swapbits(unsigned int n) {
   unsigned int E = n & 0xAA ;
   unsigned int O = n & 0x55 ;
   unsigned int result = (E >> 1)|(O << 1);
   return result;
}
int main() {
   unsigned int n = 14;
   cout << "After swapping the even position bits with off position bits, the binary number obtained is " << swapbits(n) << endl;
   return 0;
   // code is contributed by Vaishnavi tripathi
}

輸出

After swapping the even position bits with off position bits, the binary number obtained is 13

時間複雜度 - 此方法的時間複雜度為 O(1)。

空間複雜度 - 我們沒有使用任何額外的空間。輔助空間複雜度為 O(1)。

更新於:2023年8月16日

315 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.