Interview questions 05.07. Paired exchange

topic:

Paired exchange. Programming, switching to an integer odd bit and the even bit, try to use fewer instructions (i.e., bits 0 and 1 bit exchange, the exchange bit 2 bit 3, and so on).

Example 1:

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

Input: num = 3
Output: 3
Note:

num range between - [0, 2 ^ 301], integer overflow does not occur.

 

answer:

Honest method:

class Solution {
public:
    int exchangeBits(int num) {
        int x1,x2;
        for(int i=1;i<32;i+=2){
            x1=num&(1<<i);
            x2=num&(1<<(i-1));
            if(x1){
                num|=(x1>>1);
            }
            else{
                if(x2){
                    num^=(1<<(i-1));
                }
            }
            if(x2){
                num|=(x2<<1);
            }
            else{
                if(x1){
                    num^=(1<<i);
                }
            }
        }
        return num;
    }
};

Comments area method, stunned:

First screening odd bits, even bit and then screened. The former right one, which left one and then seek or.

class Solution {
public:
    int exchangeBits(int num) {
        int odd = 0x2aaaaaaa & num;
        int even = 0x15555555 & num;
        odd >>= 1;
        even <<= 1;
        return odd | even;
    }
};

 

Guess you like

Origin www.cnblogs.com/FdWzy/p/12617129.html