Program opened below. You can scroll through the algorithm, Java code and output.

Hamming Distance of Binary Strings

Download .java

Question

Read two binary strings of equal length and calculate the number of positions at which their corresponding bits differ.

Step 1: Start and read the first binary string. Step 2: Read the second binary string. Step 3: Compare their string lengths. Step 4: Reject inputs of unequal length. Step 5: Initialize a distance counter to zero. Step 6: Position the loop at the first bit. Step 7: Read the corresponding bit from each input. Step 8: Check that both characters are binary digits. Step 9: Reject the input if a character is not zero or one. Step 10: Compare the two bits. Step 11: If the bits differ, increment the distance. Step 12: Advance the position by one. Step 13: Repeat through the entire length. Step 14: Print the resulting Hamming distance. Step 15: Stop.
Java
import java.util.*;
class HammingDistance {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String a = sc.next();
        String b = sc.next();
        if (a.length() != b.length()) {
            System.out.println("Unequal lengths");
            return;
        }
        int distance = 0;
        for (int i = 0; i < a.length(); i++) {
            char x = a.charAt(i);
            char y = b.charAt(i);
            if ((x != '0' && x != '1') || (y != '0' && y != '1')) {
                System.out.println("Invalid binary input");
                return;
            }
            if (x != y) {
                distance++;
            }
        }
        System.out.println("Hamming distance = " + distance);
    }
}
Input: 10101 11100 Output: Hamming distance = 2
← Previous Program 28 of 84 Next →

Share a comment or request a program

Use this form to send a comment, report an issue, or suggest a new practical. Your message will be saved for review by the school.