面试题 05.07. 配对交换 #
题目 #
配对交换,编写代码,交换某个整数的奇数位和偶数位,尽量使用较少的指令。
即将位0与位1交换,位2与位3交换,以此类推。
思路 #
- 位运算
代码 #
local picture #
class Solution {
public int exchangeBits(int num) {
int odd = 1 << 1, even = 1 << 0;
while (0 <= odd && odd <= (1 << 29)) {
if (((num & odd) != 0) && (num & even) == 0) || (num & odd) == 0 && (num & even) != 0) {
num ^= odd ^ even;
}
odd <= 2;
even <= 2;
}
return num;
}
}
global picture #
class Solution {
public int exchangeBits(int num) {
return ((num & 0xaaaaaaaa) >> 1) | ((num & 0x55555555) << 1);
}
}