n個數,將其中的偶數的二進制反轉
比如,輸入1 6 5
6是偶數,二進制110,翻轉後011,代表3,最終輸出1 3 5
輸入描述:
輸入包含多組測試數據
對於每一組測試數據:
N——輸入的字數
N個數:a0,a1,a2……,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
解決方案有兩種:
1.轉化成2進制字符串然後倒轉字符數組
import java.util.Scanner;
/**
* Created by Feng on 2016/6/21.
*/
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()){
int n = scanner.nextInt();
int src[] = new int[n];
for (int i = 0; i < n; i++) {
src[i] = scanner.nextInt();
}
for (int i = 0; i < n; i++) {
if((src[i]&1)==0){
src[i] = Integer.parseInt(reve(Integer.toBinaryString(src[i])),2);
}
}
for (int i = 0; i <n ; i++) {
System.out.print(src[i] + " ");
}
System.out.println();
}
}
public static String reve(String s){
char[] src = s.toCharArray();
for (int i = 0; i <src.length/2 ; i++) {
char temp = src[i];
src[i] = src[src.length-i-1];
src[src.length-i-1] = temp;
}
return new String(src);
}
}
2.按位運算
import java.util.Scanner;
/**
* Created by Feng on 2016/6/21.
*/
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()){
int n = scanner.nextInt();
int src[] = new int[n];
for (int i = 0; i < n; i++) {
src[i] = scanner.nextInt();
}
for (int i = 0; i < n; i++) {
if((src[i]&1)==0){
int temp = src[i];
while((temp&1)==0) temp = temp>>1;
src[i] = 1;
temp = temp>>1;
while(temp>0){
src[i] = src[i]<<1;
if((temp&1)==0){
}else{
src[i]+=1;
}
temp = temp>>1;
}
}
}
for (int i = 0; i <n ; i++) {
System.out.print(src[i] + " ");
}
System.out.println();
}
}
}