jayati

Swap all odd and even bits

Oct 2nd, 2023
1,163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.79 KB | None | 0 0
  1. //{ Driver Code Starts
  2. //Initial Template for C++
  3.  
  4. #include<bits/stdc++.h>
  5. using namespace std;
  6.  
  7.  
  8. // } Driver Code Ends
  9. //User function Template for C++
  10.  
  11. class Solution
  12. {
  13.     public:
  14.     //Function to swap odd and even bits.
  15.     unsigned int swapBits(unsigned int n)
  16.     {
  17.         int oddm=0x55555555;
  18.         int evenm=0xAAAAAAAA;
  19.        
  20.         int odd=n&oddm;
  21.         int even=n&evenm;
  22.        
  23.         odd=odd<<1;
  24.        
  25.         even=even>>1;
  26.        
  27.         n=odd|even;
  28.         return n;
  29.     }
  30. };
  31.  
  32. //{ Driver Code Starts.
  33.  
  34. // Driver code
  35. int main()
  36. {
  37.     int t;
  38.     cin>>t;//testcases
  39.     while(t--)
  40.     {
  41.         unsigned int n;
  42.         cin>>n;//input n
  43.        
  44.         Solution ob;
  45.         //calling swapBits() method
  46.         cout << ob.swapBits(n) << endl;
  47.     }
  48.     return 0;
  49. }
  50. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment