HUST 1404 Hamming Distance(字符串)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HUST 1404 Hamming Distance(字符串)相关的知识,希望对你有一定的参考价值。

Hamming Distance

Description

Have you ever heard of the Hamming distance. It is the number of positions for which the corresponding digits differ. Your task is to write a program that computes this distance for two binary strings.

Input

The input contains several test cases. Each test case consists of two lines. Each line contains one binary number. Any two numbers given in one test case have the same length, which is at most 100 binary digits. The last test case is followed by a line containing the uppercase letter "X".

Output

Your program must output a single line for each test case. The line should contain the statement "Hamming distance is X.", where X is the number of positions where the two numbers have different digits.  

Sample Input

0
1
000
000
1111111100000000
0000000011111111
101
000
X

Sample Output

Hamming distance is 1.
Hamming distance is 0.
Hamming distance is 16.
Hamming distance is 2.

题解:读取两个相同长度字符串,从第一位往后对比,如果不一样,ans++。X结束。

技术分享
#include <cstdio>
#include <iostream>
#include <string>
#include <sstream>
#include <cstring>
#include <stack>
#include <queue>
#include <algorithm>
#include <cmath>
#include <map>
#define PI acos(-1.0)
#define ms(a) memset(a,0,sizeof(a))
#define msp memset(mp,0,sizeof(mp))
#define msv memset(vis,0,sizeof(vis))
using namespace std;
//#define LOCAL
int main()
{
#ifdef LOCAL
    freopen("in.txt", "r", stdin);
#endif // LOCAL
    ios::sync_with_stdio(false);
    char a[120],b[120];
    while(cin>>a&&a[0]!=X)
    {
        cin>>b;
        int ans=0;
        for(int i=0,s=strlen(a);i<s;i++)
        {
            if(a[i]!=b[i])ans++;
        }
        printf("Hamming distance is %d.\n",ans);
    }
    return 0;
}
View Code

 

以上是关于HUST 1404 Hamming Distance(字符串)的主要内容,如果未能解决你的问题,请参考以下文章

Hamming(7,4)编译码器

位运算——Hamming Distance

Hamming Codes

LeetCode 477: Total Hamming Distance

Hamming校验码

洛谷 P1461 海明码 Hamming Codes