Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- 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.
- Input format
- N which represents an unsigned integer.
- Output format
- Single output integer after the algorithm has successfully swapped bits of the input.
- Constraints
- 0 <= N <= 2147483647
- Sample Input 1
- 22
- Sample Output 1
- 41
- Explanation 1
- The given number is 22 (00010110), it should be converted to 41 (00101001).
- Sample Input 2
- 13
- Sample Output 2
- 14
- Explanation 2
- The given number is 13 (00001101), it should be converted to 14 (00001110).
- */
- /**
- * @param {number} n - a positive integer
- * @return {number} - a positive integer
- */
- // https://www.youtube.com/watch?v=GbH8PcqKosk&list=TLGGHEnkmm6absoxODA4MjAyMQ
- function swapAllOddAndEvenBits(n) {
- // Implement it here
- let maskOddBits=toUnsigned32Bits(0xAAAAAAAA); // 1010 1010..
- let maskEvenBits=toUnsigned32Bits(0x55555555);// 0101 0101
- let onlyEvenBits=toUnsigned32Bits(n&maskOddBits);
- let onlyOddBits=toUnsigned32Bits(n&maskEvenBits);
- onlyEvenBits=toUnsigned32Bits(onlyEvenBits>>1);
- onlyOddBits=toUnsigned32Bits(onlyOddBits<<1);
- return toUnsigned32Bits(onlyEvenBits|onlyOddBits);
- /*
- for(let i=0;i<32;i=i+2){
- let ithBit=n&(1<<(i-1));//
- let iPlus1thBit=n&(1<<(i));
- // calculatn for ith bit
- if(iPlus1thBit==1){
- n=n|(1<<i-1);
- }
- else
- n=n&(0<<i-1);
- // calculation for i+1 th bit
- if(ithBit==1){
- n=n|(1<<i);
- }
- else
- n=n&(0<<i);
- }
- return n;
- */
- }
- function main() {
- let n = parseInt(readLine(), 10);
- let answer = swapAllOddAndEvenBits(n);
- print(answer);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement