今天的计算机课上,老师给同学们出了一道题:
输入n个数,请将其中的偶数的二进制反转。
eg:输入1 6 5
其中6是偶数,二进制表示为110,反转后为011,代表3,所以最终输出1 3 5.
小贱君最近脑子不怎么好使,想了半天也没想出来如何做,最后他向你寻求帮助了,帮帮可怜的小贱君吧!
输入包含多组测试数据。
对于每组测试数据:
N --- 输入的数字个数
N个数:a0,a1,...,an-1
保证:
1<=N<=3000,0<=ai<=INT_MAX.
对于每组数据,输出N个整数。
5 1 3 10 6 7 6 26 52 31 45 82 34
1 3 5 3 7 11 11 31 45 37 17
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N; int[] a; while(sc.hasNext()){ N = sc.nextInt(); a = new int[N]; for(int i = 0; i< N; i++){ a[i] = sc.nextInt(); if(a[i] % 2==0){ a[i] = toBinary(a[i]); } } for(int i =0; i < N-1;i++){ System.out.print(a[i] + " "); } System.out.print(a[N-1]); System.out.println(); } } public static int toBinary(int x){ int m =0; StringBuilder yu = new StringBuilder(); for(int i = 0; x > 0; i++){ yu.append( x % 2); x = x / 2; } int index = 0; for(int i = yu.length()-1; i >= 0;i--){ m += (yu.charAt(i)-'0')* (1<<(yu.length()-i-1)); } return m; } }
import java.util.Scanner; public class Main{ /** * @param args */ public static void main(String[] args) { Main rEven = new Main(); rEven.reverseEven(); } public void reverseEven() { Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { int n = scanner.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; ++i) { int temp = scanner.nextInt(); if ((temp & 0x1) == 0) a[i] = reverse(temp); else a[i] = temp; } for (int i = 0; i < a.length-1 && i < n-1; i++) { System.out.print(a[i]+" "); } if(n-1>=0) System.out.println(a[n-1]); } } public int reverse(int even) { if (even == 0) return 0; int d = even; int len = Integer.toBinaryString(even).length(); int b[] = new int[len]; int i = 0; for(;i<len;i++){ b[i] = d & 0x01; d >>= 1; } d = 0; i = 0; while (i < len) { d = b[i] + d * 2; i++; } return d; } }