Skip to content

Latest commit

 

History

History
104 lines (73 loc) · 1.71 KB

README_EN.md

File metadata and controls

104 lines (73 loc) · 1.71 KB

中文文档

Description

Write a program to swap odd and even bits in an integer with as few instructions as possible (e.g., bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, and so on).

Example1:

 Input: num = 2(0b10)

 Output 1 (0b01)

Example2:

 Input: num = 3

 Output: 3

Note:

  1. 0 <= num <= 2^30 - 1
  2. The result integer fits into 32-bit integer.

Solutions

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
}

...