首页 > 试题广场 >

偶数大翻转

[编程题]偶数大翻转
  • 热度指数:3462 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
今天的计算机课上,老师给同学们出了一道题:
输入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个整数。

示例1

输入

5
1 3 10 6 7
6
26 52 31 45 82 34

输出

1 3 5 3 7
11 11 31 45 37 17
#include <iostream>
using namespace std;
int flipNum(int x){
    if (x & 1) return x;
    int n = 0;
    while (x){
        n = (n << 1) | (x & 1);
        x = x >> 1;
    }
    return n;
}
int main(){
    int N;
    int x;
    while (cin >> N){
        for (int i = 0; i < N; ++i){
            cin >> x;
            cout << flipNum(x);
            if (i != N - 1) cout << " ";
        }
        cout << endl;
    }
}



编辑于 2016-06-22 12:56:52 回复(11)
import java.util.Scanner;
//注意输出的格式。。。。思路:位操作,count数组保存二进制形式的每一位。欢迎交流~
public class Main {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		while(scanner.hasNext()) {
			int n = scanner.nextInt();
			int[] num = new int[n];
            int[] res = new int[n];
			for(int i = 0; i < n; i ++) {
				num[i] = scanner.nextInt();
				if((num[i]& 1) == 0) {
					res[i] = reverse(num[i]);
				} else {
					res[i] = num[i];
				}
			}
            for(int i = 0; i < n - 1; i ++) {
               System.out.print(res[i] + " ");
            }
             System.out.print(res[n - 1]);
             System.out.println();
		}
	}

	private static int reverse(int a) {
		int res = 0;
		//count数组存储a的二进制表示,从低位到高位,如10,count[1] = 1,count[3] = 1,其余为0
		int[] count = new int[32];
		for(int i = 0; i < 32; i ++) {
			 count[i] = (a >> i) & 1;
		}
		int k = 0;
		//最高位起,除符号位外(第31位),寻找a的二进制表示中,第一个为1的位
		for(k = 30; k >= 0; k --) {
			if(count[k] == 1)
				break;
		}
		//反转
		for(int i = k; i >= 0; i --) {
			res += (count[i] << k - i);
		}
		//符号位
		res += (count[31] << 31);
        return res;
		
	}
	
}


编辑于 2016-06-24 10:55:10 回复(5)
为何没人用JavaScript?
"use strict";
const readline = require('readline');
const rl = readline.createInterface(process.stdin,process.stdout);
rl.on("line",function(ans){
        var arr = ans.split(/\s+/);
        arr = arr.slice(0,n);
        let newarr = arr.map(function(e){
            return e-0;
        }).map(function(e){
            return e.toString('2');
        }).map(function(e){
            let res ;
            if(e%2==0){
                e = e.split("").reverse().join("");

            }
            res = parseInt(e,2)
            return res;
        })
        console.log(newarr.join(" "));

        });
       rl.close();
    }else{
    throw new Error();
    }
    
})

编辑于 2016-09-08 21:58:04 回复(3)
#include <iostream>
#include <vector>
 
using namespace std;
 
int main()
{
    int num;
    while(cin>>num)
    {
        int arr;
        vector<int> vec;
        for(int i=0; i<num; ++i)
        {
            cin >> arr;
            vec.push_back(arr);
        }
 
        for(int i=0; i<num; ++i)
        {
            if(vec[i]%2== 0)
            {
                int temp = vec[i];
                int str[32] = {0};
                int j=1;
                int count = 0;
                while(temp)
                {
                    ++count;
                    str[32-j] = temp%2;
                    temp/=2;
                    j++;
                }
                int* p = new int[count];
                for(int m=31,k=0;k<count;m--,++k)
                {
                          p[k] = str[m];
 
                }
                int tmp = 0;
                for(int jj=count-1; jj>=0;--jj)
                {
                    int aaa;
                    int sum = 0;
                    if(p[jj] == 1)
                    {
                        aaa = 1;
                        for(int bb=0; bb<count-jj-1; ++bb)
                            aaa *= 2;
                        sum += aaa;
                    }
                    tmp += sum;
                }
                vec[i] = tmp;
 
 
                delete [] p;
                p = NULL;
            }
        }
        for(int i=0; i<num-1; ++i){
            cout << vec[i] << " ";
			if(i==num-2)
				cout << vec[num-1] << endl; 
        }
            
        
    }
    
 
    return 0;
}

编辑于 2016-07-29 16:45:30 回复(9)
#include <iostream>
#include <string>
#include <math.h>
using namespace std;
int main() {
	unsigned int N, a;
	while (cin >> N) {
		for (int i = 1; i <= N; i++) {
			cin >> a;
			if (!(a % 2)) {
				string str;
				while (a) {
					str.insert(str.length(), 1, a % 2);
					a /= 2;
				}
				for (int i = 0; i < str.length(); i++)
					a += str[i] * pow(2, str.length() - 1 - i);
			}
			cout << a << " ";
		}
		cout << endl;
	}
	return 0;
}

//思考五分钟,写代码十分钟,压缩代码一小时。。。。PS:直接模拟算了

发表于 2016-07-14 18:16:49 回复(1)
#include <iostream>
using namespace std;
int flipNum(int x){
    if (x & 1) return x;//x&1实际上就是取x二进制最左边的数,即判断奇偶
    int n = 0;//n先定义位0,作为x的翻转
    while (x){
        n = (n << 1) | (x & 1);//将x的左边的数放到n上并且左移n
        x = x >> 1;//将x右移使得下次循环在获得左边的数
    }
    return n;
}
int main(){
    int N;
    int x;
    while (cin >> N){
        for (int i = 0; i < N; ++i){
            cin >> x;
            cout << flipNum(x);
            if (i != N - 1) cout << " ";
        }
        cout << endl;
    }
}

发表于 2016-11-04 15:39:07 回复(0)
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;
	}
}

发表于 2016-08-27 13:42:57 回复(0)
importjava.util.Scanner;
 
publicclassMain {
    publicstaticvoidmain(String[] args) {
        Scanner in = newScanner(System.in);
        while(in.hasNext()) {
            intnum = in.nextInt();
            inta[] = newint[num];
            for(inti = 0; i<num;i++) {
                a[i] = in.nextInt();
            }
            print(num,a);
        }
    }
 
    publicstaticvoidprint(intnum,int[]a) {
        for(inti= 0;i<num;i++) {
            if(a[i]%2== 0) {
                String binary = Integer.toBinaryString(a[i]);
                chartmp[] = newchar[binary.length()];
                for(intj=0;j<binary.length();j++) {
                    tmp[j] = binary.charAt(j);
                }
                String res = reverse(tmp);
                res = Integer.valueOf(res,2).toString();
                a[i] = Integer.valueOf(res);
            }
            System.out.print(a[i]);
            if(i<num-1){
                System.out.print(" ");
            }
        }
        System.out.println();
    }
    publicstaticString reverse(char[] str) {
        for(inti = 0;i<str.length/2;i++) {
            chartmp = str[i];
            str[i] = str[str.length - i - 1];
            str[str.length - i - 1] = tmp;
        }
        String res = "";
        for(inti = 0;i<str.length;i++ ) {
            res += str[i];
        }
        returnres;
    }
}

发表于 2016-08-06 14:09:53 回复(0)
思路就是先转String,记下当前二进制位数,然后反序右移32-len。
之前直接又while循环做左右移动操作,O(n^2)超出了时间。 另外就是输出格式,很坑,,不能多最后那个空格。。
importjava.util.*;
 
publicclassMain {
  
    publicstaticvoidmain(String[] args) {
        // TODO Auto-generated method stub
        Scanner scanner=newScanner(System.in);
        
        while(scanner.hasNext())
        {
            intn=scanner.nextInt();
            intarr[]=newint[n];
             
            for(inti = 0; i < arr.length; i++)
            {
                arr[i] = scanner.nextInt();
                if(arr[i] % 2==0)
                {
                    intlen=String.valueOf(Integer.toBinaryString(arr[i])).length();
                    arr[i] =(Integer.reverse(arr[i]))>>(32-len);
                     
                }
            }
            for(inti = 0; i < arr.length; i++)
            {
                System.out.print(arr[i]);
                if(i!=n-1)
                {
                    System.out.print(' ');
                }
            }
            System.out.println();
        }
        scanner.close();
    }
}
发表于 2016-08-02 11:04:32 回复(0)
#include <iostream>
 
using namespace std;

unsigned int reverseBin(unsigned int num){
    if(num%2 != 0){
        return num;
    }
	unsigned int ret = 0;
	for(int i = 0; i < 32; i++){
		ret <<= 1;
		ret = ret | (num & 1);
		num >>= 1;
	}
	while(!(ret & 1)){
		ret >>= 1;
	}
	return ret;
}

int main(){
    int n = 0;
    unsigned int num;
    while(cin >> n){
        for(int i = 0; i < n; i++){
            cin >> num;
            cout << reverseBin(num);
            if(i != n-1) cout << " ";
        }
        cout << endl;
    }
    return 0;
}

发表于 2016-07-12 15:05:45 回复(0)
我想问一下,这个二进制是怎么反转的,比如6 为110, 反转以后为011,,,,这个是把0变为1,1变为0???还是直接倒过来?? 比如8 二进制位1000,第一种反转结果是0111,第二种反转结果还是0001。
发表于 2016-06-27 11:32:56 回复(1)
VS2013调的没有问题,提交测试就是通不过,也是醉了。。
#include<iostream>
#include<math.h>
using namespace std;
int main(){
int i, j, N, len, temp;
while (cin >> N && N > 1 && N < 3000){
int *input = new int[N];
int *output = new int[N];
for (i = 0; i < N; i++){
cin >> input[i];
}
for (i = 0; i < N; i++){
if (input[i] % 2 == 0){
len = 1;
while (pow(2, len + 1) <= input[i])
len++;
int *revert = new int[len];
temp = input[i] / 2;
j = 0;
while (temp != 1){
if (temp % 2 == 0)
revert[j] = 0;
else
revert[j] = 1;
temp = temp / 2;
j++;
}
revert[j] = 1;
for (output[i] = 0, j = len - 1, temp = 1; j >= 0; j--){
output[i] += temp*revert[j];
temp *= 2;
}
delete [] revert;
}
else
output[i] = input[i];
}
for (i = 0; i < N; i++)
cout << output[i] << " ";
delete [] input;
delete [] output;
}
return 0;
}

编辑于 2016-06-25 11:34:22 回复(3)

import java.util.Scanner;


public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
int N = scan.nextInt();
int[] a = new int[N];
for(int i = 0;i<N;i++){
a[i] = scan.nextInt();
if(a[i]%2==0){
char bArr[] = Integer.toBinaryString(a[i]).toCharArray();
int sum = 0;
int flag = 0;
for(int j = 0;j<bArr.length;j++){
int tempJ = Integer.valueOf(String.valueOf(bArr[j]));
sum += Math.pow(2, flag)*tempJ;
flag++;
}
a[i] = sum;
} //if
}
for(int k = 0;k<N-1;k++){
System.out.print(a[k]+" ");
}
System.out.println(a[N-1]);
} // while
} //main
}

发表于 2016-06-21 23:26:55 回复(0)
var readline = require('readline'); 
rl = readline.createInterface({ 
      input: process.stdin, 
      output: process.stdout 
  }); 
  var n = 0; 
  rl.on('line', function(line) { 
      var data = line.trim().split(' '); 
      var result=[];
      if(data.length == 1) { 
          n = parseInt(data[0]); 
      }else if(data.length == n) { 
          result = data.map(function(val, index) { 
              if(val % 2== 0) { 
                  return parseInt(parseInt(val).toString(2).split('').reverse().join(''), 2).toString(10);
              }else{ 
                  return val; 
              } 
          }); 
          console.log(result.join(' ')); 
          n = 0; 
      } 
});


发表于 2017-08-07 20:40:32 回复(0)
我用java代码实现如下:

import java.util.Scanner;

public class Main {

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while(scan.hasNextInt()){
int a = Integer.parseInt(scan.nextLine());
String[] s = scan.nextLine().split(" ");//利用空格进行拆分
for(int i = 0;i<s.length;i++){
int b = Integer.parseInt(s[i]);//取每一个数判断奇偶
if(b%2==0){//此时为偶数 ,并计算他的二进制存入字符串ss中
String ss = "";
while(b!=0){
ss = b%2+ss;
b=b/2;
}//算完时b为0
for(int j=0;j<ss.length();j++){
if(ss.charAt(j)=='1'){
b = (int) (b + Math.pow(2, j));//并计算它反向二进制的十进制数值
}
}
}
s[i] = ""+b;//把整型转换为String
}
System.out.print(s[0]);//每两个数字之间有一个空格
for(int k=1;k<s.length;k++){
System.out.print(" "+s[k]);
}
System.out.println();
}
}

}

发表于 2017-02-23 20:03:24 回复(0)
public static void main(String[] args) {
  
  Scanner sc = new Scanner(System.in);
  while (sc.hasNext()) {
   String str = sc.nextLine();
   int n = Integer.parseInt(str);
   String[] str2 = sc.nextLine().split(" ");
   for (int i = 0; i < n; i++) {
    int c = Integer.parseInt(str2[i]);
    if (c % 2 == 0) {
     String binary = Integer.toBinaryString(c);
     char[] r = binary.toCharArray();
     char[] ne = new char[binary.length()];
     int q = 0;
     for (int t = r.length - 1; t >= 0; t--) {
      ne[q] = r[t];
      q++;
     }
     int s = Integer.parseInt(String.valueOf(ne), 2);
     str2[i] = String.valueOf(s);
    }
   }
   for (String string : str2) {
    System.out.print(string+" ");
   }
   System.out.println();
  }
 }

发表于 2016-10-20 15:48:24 回复(0)

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            int N = scanner.nextInt();
            int[] firstArr = new int[N];
            for (int i = 0; i < N; i++) {
                firstArr[i] = scanner.nextInt();
            }
//只转变偶数,将其二进制各位倒序存在字符串temp中,然后调用Integer.valueOf(temp, 2);方法转为整数 for (int j = 0; j < N; j++) {
                if (firstArr[j] % 2 == 0) {
                    String temp = "";
                    while (firstArr[j] != 0) {//一直到整数部分为0
                        temp = temp + (firstArr[j] % 2);//余数,并且拼接起来,注意已经反过来了
                        firstArr[j] = firstArr[j] / 2;//除2取整
                    }
                    firstArr[j] = Integer.valueOf(temp, 2);
                } else continue;
            }

//输出要严格按照题目意思才不会出错
            for (int i = 0; i < (N-1); i++) {
                System.out.print(firstArr[i] + " ");
            }
            System.out.print(firstArr[N - 1]);
            System.out.println();
            
        }
        scanner.close();
    }

}


发表于 2016-09-28 22:25:17 回复(0)
//模拟10金子转二进制的过程,输出格式太坑
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner scanner=new Scanner(System.in);
while(scanner.hasNextInt()){
int N=scanner.nextInt();
for(int i=0;i<N;i++){
int temp=scanner.nextInt();
if (temp%2!=0) {
                    if(i==(N-1)){
                        System.out.print(temp);
                    }else{
                        System.out.print(temp+" ");
                    }
}else{
                    if(i==(N-1)){
                        System.out.print(getFZ(temp));
                    }else{
                        System.out.print(getFZ(temp)+" ");
                    }
}
}
            System.out.println();
}
}
public static int getFZ(int i){
int out=0;
int yushu=0;
while(i>0){
yushu=i%2;
i=i/2;
out=out*2+yushu;
}
return out;
}
}
发表于 2016-09-14 18:09:25 回复(0)
#include<stdio.h>
#include<math.h>
int main()
{
    int i,j,k,n,m=0,t,count;
    int a[10][20],b[100],c[10];
    while(scanf("%d\n",&n)!=EOF)
    {
        c[m]=n;
        for(i=0;i<n;i++)
        {
            scanf("%d",&a[m][i]);
        }
        m=m+1;
    }
    for(t=0;t<m;t++)
    {
        for(i=0;i<c[t];i++)
        {
count=0;
            if(a[t][i]%2==0)
            {
                k=a[t][i];
                for(j=0;k/2!=0;j++)
                {
                    b[j]=k%2;
                    if(k%2==0)
                        count=count+pow(2,j);
k=k/2;
                }
                a[t][i]=count;
             }
         }
    }
    for(i=0;i<m;i++)
    {
        for(j=0;j<c[i];j++)
            printf("%5d",a[i][j]);
        printf("\n");
    }
        
}
求问,为什么会提示发生段错误,数组越界?有大神能给解答一下么?
发表于 2016-09-02 18:58:22 回复(0)
    <script type="text/javascript">
    
    function reverse(num) {
    var i, len, numArray, result = 0;
    numArray = [];
    //分解位
    while (num != 0) {
        numArray.push(num % 2);
        num = parseInt(num / 2);
      
    }
    
     for (i = 0, len = numArray.length; i <len; i++) {
        result += numArray[i] * Math.pow(2, len - i - 1);
    }
    return result; 
}
window.onload = function(){
 

   var input =["1","6","5"];
   for (var i = 0; i < input.length; i++) {
       if(input[i]%2==0){
           input[i] = reverse(input[i]);
        }
   };
   alert(input);
}
    </script>

发表于 2016-08-31 10:41:51 回复(0)