Hamming distance between two Integers
Given two integers, the task is to find the hamming distance between two integers. Hamming Distance between two integers is the number of bits which are different at same position in both numbers.
Examples:
Input: n1 = 9, n2 = 14 Output: 3 9 = 1001, 14 = 1110 No. of Different bits = 3 Input: n1 = 4, n2 = 8 Output: 2
Approach:
- Calculate the XOR of two numbers.
- Count the number of set bits.
Below is the implementation of above approach:
C++
// C++ implementation of above approach #include <bits/stdc++.h> using namespace std; // Function to calculate hamming distance int hammingDistance( int n1, int n2) { int x = n1 ^ n2; int setBits = 0; while (x > 0) { setBits += x & 1; x >>= 1; } return setBits; } // Driver code int main() { int n1 = 9, n2 = 14; cout << hammingDistance(9, 14) << endl; return 0; } |
Java
// Java implementation of above approach class GFG { // Function to calculate hamming distance static int hammingDistance( int n1, int n2) { int x = n1 ^ n2; int setBits = 0 ; while (x > 0 ) { setBits += x & 1 ; x >>= 1 ; } return setBits; } // Driver code public static void main(String[] args) { int n1 = 9 , n2 = 14 ; System.out.println(hammingDistance(n1, n2)); } } // This code is contributed by Bilal |
Python3
# Python3 implementation of above approach # Function to calculate hamming distance def hammingDistance(n1, n2) : x = n1 ^ n2 setBits = 0 while (x > 0 ) : setBits + = x & 1 x >> = 1 return setBits if __name__ = = '__main__' : n1 = 9 n2 = 14 print (hammingDistance( 9 , 14 )) # this code is contributed by Smitha Dinesh Semwal |
C#
// C# implementation of above approach class GFG { // Function to calculate // hamming distance static int hammingDistance( int n1, int n2) { int x = n1 ^ n2; int setBits = 0; while (x > 0) { setBits += x & 1; x >>= 1; } return setBits; } // Driver code static void Main() { int n1 = 9, n2 = 14; System.Console.WriteLine(hammingDistance(n1, n2)); } } // This code is contributed by mits |
PHP
<?PHP // PHP implementation of above approach // Function to calculate hamming distance function hammingDistance( $n1 , $n2 ) { $x = $n1 ^ $n2 ; $setBits = 0; while ( $x > 0) { $setBits += $x & 1; $x >>= 1; } return $setBits ; } // Driver code $n1 = 9; $n2 = 14; echo (hammingDistance(9, 14)); // This code is contributed by Smitha ?> |
Output:
3
Note: No. of set bits can be count using __builtin_popcount() function.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.