首页 > 试题广场 >

奇偶校验

[编程题]奇偶校验
  • 热度指数:10087 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
输入一个字符串,然后对每个字符进行奇校验,最后输出校验后的二进制数(如'3’,输出:10110011)。

输入描述:
输入包括一个字符串,字符串长度不超过100。


输出描述:
可能有多组测试数据,对于每组数据,
对于字符串中的每一个字符,输出按题目进行奇偶校验后的数,每个字符校验的结果占一行。
示例1

输入

3
3a

输出

10110011
10110011
01100001
#include <iostream>
#include <string>
#include <bitset>

int main()
{
	std::string str;
	while (std::cin >> str)
	{
		for (auto c : str)
		{
			std::bitset<8> bit(c);
			if (bit.count() % 2 == 0)
			{
				bit[7] = 1;
			}
			std::cout << bit << std::endl;
		}
	}
	return 0;
}

发表于 2017-05-17 10:49:13 回复(0)
Java 解法
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()){
            String s = scanner.next();
            char[] array = s.toCharArray();
            for (char c : array) {
                String s1 = Integer.toBinaryString(c);
                String s2 = String.format("%07d", Integer.parseInt(s1));
                int count = 0;
                for (int j = 0; j < 7; j++) {
                    if (s2.charAt(j) == '1') count++;
                }
                System.out.println(count % 2 == 0 ? "1" + s2 : "0" + s2);
            }
        }
    }
}


发表于 2020-03-14 19:19:53 回复(0)
//the Java version
import java.util.*; public class Main{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        while(in.hasNext()){
            String str = in.nextLine();
            jiCheck(str.toCharArray());
        }
    }
    public static void jiCheck(char[] s){
        int[] result = new int[8];
        for(int i = 0; i < s.length; i++){
            int oneNum = 0;
            int one = 0x01;
            int index = 7;
            while(index > 0){
                result[index] = ((s[i] & one) == 0) ? 0 : 1;
                if(result[index] == 1) oneNum++;
                one <<= 1;
                index--;
            }
            if(oneNum % 2 == 0) result[0] = 1;
            for(int k = 0; k < 8; k++){
                System.out.print(result[k]);
            }
            System.out.println();
            result[0] = 0;//update
        }
    }
}

发表于 2017-05-20 17:33:37 回复(0)
#include <bits/stdc++.h>

using namespace std;

//'3' = 0110011 ----- 1 0110011
//'a' = 1100001 ----- 0 1100001
int arr[8] = {0};
int main()
{
    string str;
    while(cin>>str)
    {
        int strSize = str.size();
        int num = 0;//读出str的值
        for(int i = 0; i < strSize; i++)
        {
            int cnt = 0;//记录1出现的次数
            memset(arr,0,sizeof(arr));
            int j = 0;
            num = str[i] - '\000';
            do{
                arr[j++] = num % 2;
                if(num % 2 == 1) cnt++;
                num /= 2;
            }while(num != 0);
            if(cnt % 2 == 1) arr[7] = 0;
            else arr[7] = 1;
            for(int k = 7; k >= 0; k--)
            {
                printf("%d",arr[k]);
            }
            printf("\n");
        }
    }
    return 0;
}

发表于 2021-03-02 10:58:01 回复(0)
#include <iostream>
#include <string>

using namespace std;
void check_8bit(int (&result)[8],int dec);

int main(){
    string str;
    int dec,result[8];
    while(cin>>str){
        for(auto c:str){
            dec=c-'\0';
            check_8bit(result,dec);
            for(int i=0;i<8;++i){
                cout<<result[i];
            }
            cout<<endl;
        }
    }
    return 0;
}

void check_8bit(int (&result)[8],int dec){
    int flag=0;
    for(int i=7;i>0;--i,dec/=2){
        result[i]=dec%2;
        if(dec%2==1){
            flag++;
        }
    }
    if(flag%2==0)
        result[0]=1;
    else
        result[0]=0;
}

编辑于 2020-03-09 16:44:04 回复(0)
Java解法:
思路:
1.字符--->整数
2.判断二进制整数中 1 的个数:让其每一位与对应的位数为1的数字相与,如果为1则计数器+1
3.判断计数器值是否为偶数,为偶数则最高位(第八位)置1,完成奇校验
4.整数换为二进制输出(字符串拼接)
import java.util.*;

public class Main{
    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        while(in.hasNext()) {
            String s=in.nextLine();
            for (int i=0;i<s.length();i++){
                int ch=s.charAt(i);
                if (c(ch)%2==0){ //若1的个数为偶数
                   ch+=128;
               }
                System.out.println(num(ch));
            }
        }
    }
      public static int c(int n){//判断二进制整数中 1 的个数         
            int count=0;
        int b=1;
        for (int i=0;i<8;i++){
            if ((n & b)==b){
                count++;
            }
            b=(b<<1);
        }return count;
    }
         
      public static String num(int n){//整数换为二进制输出         
            int b=128;
        StringBuilder string=new StringBuilder();
        for (int i=0;i<8;i++){
            if ((n & b)==b){
                string.append("1");
            }else{
                string.append("0");
            }
            b=(b>>>1);
        }return string.toString();
    }
}

编辑于 2019-08-02 21:36:33 回复(0)
#include <stdio.h>
#include <string.h>
int main(){
    char str[100];
    while(scanf("%s",str)!=EOF){
        int len=strlen(str);
        for(int i=0;i<len;i++){
            int count=0;
            int num=str[i];
            char output[8];
            int index=0;
            for(int i=0;i<8;i++){
                output[i]='0';
            }
            while(num!=0){
                int r=num%2;
                if(r==1){
                    count++;
                    output[index]='1';
                }else{
                    output[index]='0';
                }
                num=num/2;
                index++;
            }
            if(count%2==0){
                output[7]='1';
            }
            for(int i=7;i>=0;i--){
                printf("%c",output[i]);
            }
            printf("\n");
        }
    }
    return 0;
}

发表于 2019-02-01 12:26:15 回复(0)

建议这道题可以直接去看java的源码

Integer.toBinaryString();

这个源码里面调用了一个

toUnsignedString()

我就是参考这个代码写的~

发表于 2017-05-24 12:09:53 回复(0)
/*思想就是:转为2进制后1的个数为偶数最高位要补1,注意ascii码最大就是127*/
int main()
{
	char c;
	int i;
	bitset<8> bit; 
	while(cin>>c)
	{
		if(c == ' ' || c == '\n')
			continue;
		bit = c;
		if((bit.count() & 1) == 0)
			bit.set(7);
		cout<<bit<<endl;
	}
	return 0;
}

发表于 2017-03-19 16:58:00 回复(0)
//核心思想是用与运算得出ASCII码的二进制形式和ASCII字符中1的个数
import java.util.Scanner;

public class Main{
	
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		while(in.hasNext()){
			String str = in.nextLine();
			jiQiaoYan(str.toCharArray());
		}
	}
	
	public static void jiQiaoYan(char[] s){
		int[] result = new int[8];
		for(int i = 0; i < s.length; i++){
			int n = 0x01;
			int j = 7;
			int sum = 0;
			while(j > 0){    //需要进行7次与运算,得出1的个数 及 二进制形式
				result[j] = (s[i] & n) == 0 ? 0 : 1;    //与运算
				if(result[j] == 1) sum++;    //个数
				n = n << 1;
				j--;
			}
			
			if((sum & 1) == 0) result[0] = 1;    //进行校验
			for(int k = 0; k < result.length; k++){
				System.out.print(result[k]);
			}
			result[0] = 0;
			System.out.println();
		}
	}
}	


发表于 2017-03-10 02:50:28 回复(0)
while True:
    try:
        for c in raw_input():
            s = '{:07b}'.format(ord(c))
            print '1' + s if s.count('1') & 1 == 0 else '0' + s
    except EOFError:
        break

编辑于 2017-01-06 21:31:55 回复(0)
#include<iostream>
#include<cstring>
using namespace std;
//'3' 的十进制为51,需要'3'减去'\0'才能得到十进制,二进制为00110011
int main(void)
{
    string s;
    int a[8];//存储字符的二进制数
    
    while(cin >> s)
    {
        int c;
        int count;
        
        for(int i = 0;i < s.size();i++)
        {
            memset(a, 0, sizeof(a));//重新初始化数组a
            count = 0;
            c = s[i] - '\0';//得到字符的十进制表示
            int j = 0;
            while(c != 0)//模2除法
            {
                int temp = c % 2;
                a[j++] = temp;
                if(temp == 1)
                    count++;
                c /= 2;
            }
            if(count % 2 == 0)
                a[7] = 1;
            else
                a[7] = 0;;
            
            for(int i = 7;i >= 0;i--)
                cout << a[i];
            cout << endl;
        }
    }
    return 0;
}

编辑于 2021-03-15 21:02:04 回复(0)
//又学到了一个好玩的bitset
#include<bits/stdc++.h>
using namespace std;
int main()
{
    bitset<8> bs;
    string s;
    string::iterator sit;
    while (cin>>s)
    {
        
        for ( sit = s.begin(); sit !=s.end(); sit++)
        {
            bs = (*sit);
            if (bs.count() % 2 == 0) bs.set(7, 1);
            cout << bs<<endl;
        }
        s.clear();
    }
    return 0;
}

发表于 2018-07-19 10:45:59 回复(0)
#include<iostream>
using namespace std;

int main() {
	char str[128];
	for (; cin >> str;) {
		for (int n = 0; str[n]; n++) {
			str[n] |= 0x80;
			for (int i = 0; i < 7; i++) {
				str[n] += (char)(((str[n] >> i) & 0x01) << 7);
			}
		}
		for (int n = 0; str[n]; n++, cout << endl) {
			for (int i = 7; i > -1; i--) {
				cout << ((str[n] >> i) & 0x01);
			}
		}
	}
	return 0;
}

发表于 2017-03-22 22:18:42 回复(0)
这一题里面将数字和字母统一看成是char类型的,所以数字3实际存储时为ASCII码中的‘3’,其十进制表示是51,转化为二进制表示就是0110011,取最高位为奇校验位,校验位为1,所以校验后的二进制数为10110011,字母同理。故本题只需将输入的字符减去‘\0’得到字符的十进制表示,再将其转化为七位二进制数加上一位校验位输出即可。
发表于 2018-03-11 11:06:58 回复(11)
#include<stdio.h>
int main()
{
    char a[100];
    int b[8],i;
    while(scanf("%s",a)!=EOF)
    {
        int sum,c=0;
        while(a[c]!='\0')
        {
            sum=0;
            for(i=7;i>=1;i--)
            {
                b[i]=a[c]%2;
                a[c]=a[c]/2;
            }
        for(i=7;i>=1;i--)
            sum+=b[i];
        if(sum%2==0) b[0]=1;
            else b[0]=0;
        for(i=0;i<8;i++)
            printf("%d",b[i]);
            printf("\n");
            c++;
        }
    }
    return 0;
}

发表于 2017-12-30 21:14:59 回复(1)

python3解法:

这个题就是找输入的字符的8位(ascii=>bin)表示中1的个数,如果1的个数为偶数,就把最高位置1.


while True:
    try:
        string=input()
        for i in string:
            res=bin(ord(i)).replace("0b","").rjust(8,"0")
            print("1"+res[1:] if res.count("1")%2==0 else res)

    except:
        break
发表于 2017-10-17 09:05:47 回复(0)
//纯c位运算
#include<stdio.h>
int main(){
    char s[110];
    while(~scanf("%s",s)){
        int i;
        for(i=0;s[i];i++){
            int m=1,pos;
            for(pos=0;pos<7;pos++)
                m^=(s[i]>>pos)&1;
            m=(m<<7)|s[i];
            for(pos=7;pos>=0;pos--)
                printf("%d",(m>>pos)&1);
            printf("\n");
        }
    }
    return 0;
}
编辑于 2018-02-21 22:17:35 回复(0)
fat头像 fat
有人能比我更最简洁吗~

#include<iostream>
#include<bitset>
using namespace std;
int main()
{
	char chr;
	while (cin >> chr)
	{
		int sign = 1;
		for (int i = 0; i < 8; ++i)
            if(chr&(1 << i))
			    sign ^= 1;
		chr |= sign << 7;
		cout << bitset<8>(chr) << endl;
	}
}



编辑于 2020-04-11 20:24:28 回复(0)
1
#include<stdio.h>//读懂题目1.第一位为二进制数相加为偶则第一位为1,为奇第一位为0
#include<string.h>//2.每个字符转换成的二进制要求是七位,不够则前补0
int main()
{
    int a[1000],i,j,k,n,num,sum;
    char str[100];scanf("%s",str);
    n=strlen(str);
    for(i=0;i<n;i++)
    { 
        int s=(int)str[i];num=0;//得到字符的ascll码
        while(s)//别忘了此刻得到的结果是倒序的
        {
            a[num]=s%2;s/=2;num++;//num为二进制个数下标0-num-1
        }
        sum=0;
        for(k=0;k<num;k++)
            sum+=a[k];//看1的个数
        if(sum%2==0//判断奇偶
            printf("1");)//偶数
        else printf("0");//奇数
        while(num<7)//不够七位的二进制数前补0//按要求后七位应是该字符的二进制数
        {
            a[num]=0; num++;
        }
        for(j=num-1;j>=0;j--)//0-num为a[]的下标
            printf("%d",a[j]);
        printf("\n");
    }
}


编辑于 2020-03-29 16:19:50 回复(0)