Eighty-two. Swap the parity bits of integers (bit operation)

Swap the parity of an integer

import java.util.Scanner;

public class LianXi {
    
    
	public static int exchange(int i){
    
    
		//和10101010……做与运算取出偶数位
		int ou = i & 0xaaaaaaaa;   
		//和01010101……做与运算取出奇数位
		int ji = i & 0x55555555;
		//偶数位和奇数位异或连起来返回的值为交换后的值
		return ((ou >> 1) ^ (ji << 1));
	}
	public static void main(String[] args){
    
    
		Scanner in = new Scanner(System.in);
		int a = in.nextInt();
		int b = exchange(a);
		System.out.println(b);
	}	
}

Insert picture description here

Guess you like

Origin blog.csdn.net/JiangYu200015/article/details/112943668