Skip to content

Latest commit

 

History

History
104 lines (76 loc) · 1.91 KB

README.md

File metadata and controls

104 lines (76 loc) · 1.91 KB

English Version

题目描述

配对交换。编写程序,交换某个整数的奇数位和偶数位,尽量使用较少的指令(也就是说,位0与位1交换,位2与位3交换,以此类推)。

示例1:

 输入:num = 2(或者0b10)
 输出 1 (或者 0b01)

示例2:

 输入:num = 3
 输出:3

提示:

  1. num的范围在[0, 2^30 - 1]之间,不会发生整数溢出。

解法

Python3

class Solution:
    def exchangeBits(self, num: int) -> int:
        return ((num & 0x55555555) << 1) | ((num & 0xaaaaaaaa) >> 1)

Java

class Solution {
    public int exchangeBits(int num) {
        return ((num & 0x55555555) << 1) | ((num & 0xaaaaaaaa)) >> 1;
    }
}

Rust

impl Solution {
    pub fn exchange_bits(mut num: i32) -> i32 {
        let mut res = 0;
        let mut i = 0;
        while num != 0 {
            let a = num & 1;
            num >>= 1;
            let b = num & 1;
            num >>= 1;
            res |= a << i + 1;
            res |= b << i;
            i += 2;
        }
        res
    }
}

C++

class Solution {
public:
    int exchangeBits(int num) {
        return ((num & 0x55555555) << 1) | ((num & 0xaaaaaaaa)) >> 1;
    }
};

Go

func exchangeBits(num int) int {
	return ((num & 0x55555555) << 1) | (num&0xaaaaaaaa)>>1
}

...