Cracking the coding interview--Q5.6

来源:互联网 发布:蜘蛛纸牌生成算法 编辑:程序博客网 时间:2024/06/06 19:21

原文:

Write a program to swap odd and even bits in an integer with as few instructions as possible (e.g., bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, etc).

译文:

写程序交换一个整数二进制表示中的奇数位和偶数位,用尽可能少的代码实现。 (比如,第0位和第1位交换,第2位和第3位交换…)


题目比较简单。分别将这个整数的奇数位和偶数位提取出来,然后移位取或即可。


package chapter_5_BitManipulation;import java.util.Scanner;/** * * 写程序交换一个整数二进制表示中的奇数位和偶数位,用尽可能少的代码实现。 (比如,第0位和第1位交换,第2位和第3位交换…) *  */public class Question_5_6 {/** * @param m * @return *  * 把int类型整数 转换成二进制表示法 *  */public static String tranceBinary(int m) {StringBuilder result = new StringBuilder();char str = ' ';for(int i=0; i< 32; i++) {if((m & 1) == 1) {str = '1';} else {str = '0';}result.append("" + str);m = m>>1;}return result.toString();}/** * @param m * @return *  * 交换二进制位数奇数和偶数位 *  */public static int swap_bits(int m) {int x = (m & 0x55555555) << 1;int y = ((m >> 1) & 0x55555555);return x | y;}public static void main(String args[]) {Scanner scanner = new Scanner(System.in);int num = scanner.nextInt();scanner.nextLine();while(num-- > 0) {int m = scanner.nextInt();scanner.nextLine();String str = tranceBinary(m);System.out.format("二进制数字 :%d \n", m);System.out.format("二进制表示 : ", m);for(int i=31; i>=0; i--) {System.out.format("%c", str.charAt(i));}System.out.format("\n");int result = swap_bits(m);System.out.format("%d 换位之后 :%d\n", m, result);String strResult = tranceBinary(result);System.out.format("二进制表示 : ", m);for(int i=31; i>=0; i--) {System.out.format("%c", strResult.charAt(i));}System.out.format("\n");}}}


0 0