题目:将整数的奇偶位互换
描述:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
//法一
String str = Integer.toString(n,2);
char[] arr = str.toCharArray();
for(int i=0;i<arr.length-1;i+=2) {
char temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
}
System.out.println(Integer.toString(n,2));
System.out.println();
for(int i=0;i<arr.length;i++) {
System.out.print(arr[i]+" ");
}
}
}
//法二:
public class Main {
public static void main(String[] args) {
// TODO 自动生成的方法存根
int a = 6;
int b = m(6);
Assertions.aeertThat(b).isEqualTo(9); // Assertions是他自己写的方法
}
public static int m(int i) {
int ou = i&0xaaaaaaaa; //和1010 1010 1010 。。。。做与运算取出偶数位
int ji = i&0x55555555; //和0101 0101 0101.。。。。做与运算取出奇数位
return (ou>>1)^(ji<<1); //连起来
}
}