Advertisement
satishfrontenddev5

Untitled

Jan 6th, 2024
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. Given an unsigned integer N, swap all odd bits with even bits. Every even position bit is swapped with the adjacent bit on the right side and every odd position bit is swapped with adjacent on the left side. Assume a 32 bit integer.
  3.  
  4. Input format
  5. N which represents an unsigned integer.
  6.  
  7. Output format
  8. Single output integer after the algorithm has successfully swapped bits of the input.
  9.  
  10. Constraints
  11. 0 <= N <= 2147483647
  12.  
  13. Sample Input 1
  14. 22
  15.  
  16. Sample Output 1
  17. 41
  18.  
  19. Explanation 1
  20. The given number is 22 (00010110), it should be converted to 41 (00101001).
  21.  
  22. Sample Input 2
  23. 13
  24.  
  25. Sample Output 2
  26. 14
  27.  
  28. Explanation 2
  29. The given number is 13 (00001101), it should be converted to 14 (00001110).
  30. */
  31.  
  32. /**
  33.  * @param {number} n - a positive integer
  34.  * @return {number} - a positive integer
  35.  */
  36. // https://www.youtube.com/watch?v=GbH8PcqKosk&list=TLGGHEnkmm6absoxODA4MjAyMQ
  37. function swapAllOddAndEvenBits(n) {
  38.     // Implement it here
  39.     let maskOddBits=toUnsigned32Bits(0xAAAAAAAA);  // 1010 1010..
  40.     let maskEvenBits=toUnsigned32Bits(0x55555555);//  0101 0101
  41.     let onlyEvenBits=toUnsigned32Bits(n&maskOddBits);
  42.     let onlyOddBits=toUnsigned32Bits(n&maskEvenBits);
  43.     onlyEvenBits=toUnsigned32Bits(onlyEvenBits>>1);
  44.     onlyOddBits=toUnsigned32Bits(onlyOddBits<<1);
  45.     return toUnsigned32Bits(onlyEvenBits|onlyOddBits);
  46.  
  47.     /*
  48.     for(let i=0;i<32;i=i+2){
  49.         let ithBit=n&(1<<(i-1));//
  50.         let iPlus1thBit=n&(1<<(i));
  51.         // calculatn for ith bit
  52.         if(iPlus1thBit==1){
  53.             n=n|(1<<i-1);
  54.         }
  55.         else
  56.         n=n&(0<<i-1);
  57.  
  58.             // calculation for i+1 th bit
  59.         if(ithBit==1){
  60.             n=n|(1<<i);
  61.         }
  62.         else
  63.         n=n&(0<<i);
  64.  
  65.     }
  66.     return n;
  67.     */
  68. }
  69.  
  70. function main() {
  71.     let n = parseInt(readLine(), 10);
  72.     let answer = swapAllOddAndEvenBits(n);
  73.     print(answer);
  74. }
  75.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement