Given an unsigned 8-bit integer, swap its even and odd bits. The 1st and 2nd bit should be swapped, the 3rd and 4th bit should be swapped, and so on.
For example, 10101010
should be 01010101
. 11100010
should be 11010001
.
Example:
Input: str="10101010"
Output: 01010101
Approach
C++
#include <bits/stdc++.h>using namespace std;void swapBits(string &str){for (int i = 0; i < str.size(); i += 2){swap(str[i], str[i + 1]);}}int main(){string str = "10101010";swapBits(str);cout << str << "\n";}
No comments:
Post a Comment