comments | difficulty | edit_url |
---|---|---|
true |
简单 |
配对交换。编写程序,交换某个整数的奇数位和偶数位,尽量使用较少的指令(也就是说,位0与位1交换,位2与位3交换,以此类推)。
示例1:
输入:num = 2(或者0b10) 输出 1 (或者 0b01)
示例2:
输入:num = 3 输出:3
提示:
num
的范围在[0, 2^30 - 1]之间,不会发生整数溢出。
我们可以将
时间复杂度
class Solution:
def exchangeBits(self, num: int) -> int:
return ((num & 0x55555555) << 1) | ((num & 0xAAAAAAAA) >> 1)
class Solution {
public int exchangeBits(int num) {
return ((num & 0x55555555) << 1) | ((num & 0xaaaaaaaa)) >> 1;
}
}
class Solution {
public:
int exchangeBits(int num) {
return ((num & 0x55555555) << 1) | ((num & 0xaaaaaaaa)) >> 1;
}
};
func exchangeBits(num int) int {
return ((num & 0x55555555) << 1) | (num&0xaaaaaaaa)>>1
}
function exchangeBits(num: number): number {
return ((num & 0x55555555) << 1) | ((num & 0xaaaaaaaa) >>> 1);
}
impl Solution {
pub fn exchange_bits(num: i32) -> i32 {
let num = num as u32;
(((num & 0x55555555) << 1) | ((num & 0xaaaaaaaa) >> 1)) as i32
}
}
class Solution {
func exchangeBits(_ num: Int) -> Int {
let oddShifted = (num & 0x55555555) << 1
let evenShifted = (num & 0xaaaaaaaa) >> 1
return oddShifted | evenShifted
}
}