题目
将整数的二进制奇偶位互换
给定你一个整数 n
,返回它的二进制奇偶位互换后表示的数。
示例 1:
输入: n = 6
输出: 9
解释:
6 的二进制表示: 00000000000000000000000000000110
奇偶位互换后: 00000000000000000000000000001001 表示为 9
示例 2:
输入: n = 0b01000000_00000000_00000000_00000000
输出: 0b10000000_00000000_00000000_00000000
解题
方法一:位运算
思路
代码
class Solution {
public int swapOddAndEvenBits(int n) {
int even = n & 0xAAAAAAAA;
int odd = n & 0x55555555;
return (even >> 1) ^ (odd << 1);
}
}
import java.util.*;
import java.io.*;
public class Main {
static final int A = 0b10101010101010101010101010101010;
static final int B = 0b01010101010101010101010101010101;
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
int evenBits = n & A;
int oddBits = n & B;
System.out.println((evenBits >> 1) ^ (oddBits << 1));
}
}
评论区