LeetCode interview question 05.07. Pair exchange

Article directory

1. Title

  Pair exchange. Write a program that swaps the odd and even bits of an integer using as few instructions as possible (that is, swap bit 0 with bit 1, bit 2 with bit 3, and so on).

Example 1:

Input: num = 2 (or 0b10)
Output : 1 (or 0b01)

Example 2:

Input: num = 3
Output: 3

hint:

  • numThe range is [0, 2^30 - 1]between and no integer overflow will occur.

  Click here to jump to the question .

2. Java problem solving

  It's relatively simple, just put the code directly.

class Solution {
    
    
    public int exchangeBits(int num) {
    
    
        int ans = 0, even, odd;

        for (int i = 0; i < 32; i += 2) {
    
    
            even = 1 << i;
            odd = 1 << (i + 1);
            if ((num & even) != 0) ans |= odd;
            if ((num & odd) != 0) ans |= even;
        }

        return ans;
    }
}
  • Time: 0 ms, beats 100.00% of users using Java
  • Memory: 36.79 MB, beats 96.88% of users using Java

Guess you like

Origin blog.csdn.net/zheliku/article/details/133360700