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

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

WBOY
發布: 2023-09-11 23:01:02
轉載
1418 人瀏覽過

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

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

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 << 1以獲得所需的位置。

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 << 1

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

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

#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
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板