首頁  >  文章  >  後端開發  >  交換每兩個位元組中的每兩個位

交換每兩個位元組中的每兩個位

WBOY
WBOY轉載
2023-09-11 23:01:021408瀏覽

交換每兩個位元組中的每兩個位

在本文中,我們將討論交換給定數字中的每個交替位元的程式碼解決方案,並傳回結果數字。我們將使用位元操作的概念來解決這個問題,以便在不使用任何循環的情況下以恆定時間解決問題。

Problem statement − We are given a number n, we have to swap the pair of bits that are adjacent to each other.

In other words, we have to swap every odd placed bit with its adjacent even placed bit.

Constrain: While solving the problem, we have to keep In mind that we cannot use a loop for this problem, we have to execute our code in O(1) time complexity only.

Example

Input − n = 10011110

輸出 - 在交換偶數位置位和奇數位置位元之後,

the binary number obtained is: 01101101

Input − n = 10011110

輸出 - 在交換偶數位置位和奇數位置位元之後,

the binary number obtained is: 01101101

Explanation

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

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

For the result, we want the even position bits at the odd position and vice-versa

For even position bits at odd position,

We need to right shift the even position by one position.

因此,對於偶數位置的位,我們只需將 E >> 1 來取得所需的位置。

Similarly, we have to left shift the odd position bits by one position to get the desired position of odd bits.

所以,對於奇數位,我們只需要將O

Now the next problem is to extract the odd and even position bits.

正如我們所知,

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

Hence to extract E from n, we just need to perform

E = n & 0xAA

Similarly, to extract O from n, we need to perform-

O = n & 0x55

Now, to find the swapped output,

步驟

涉及的步驟為-

  • E >> 1

  • O

  • Now, we combine E and O using or operation.

  • #Hence our result will be – Result = ( E >> 1 | O

#Example

的中文翻譯為:

範例

這種方法的程式碼表示如下:

#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
}

Output

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

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

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

以上是交換每兩個位元組中的每兩個位的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除