Skip to content
Programming101
Programmingoneonone
  • Home
  • CS Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programming101
Programmingoneonone

Leetcode Hamming Distance problem solution

YASH PAL, 31 July 2024

In this Leetcode Hamming Distance problem solution The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, return the Hamming distance between them.

Leetcode Hamming Distance problem solution

Problem solution in Python.

class Solution:
    def hammingDistance(self, x: int, y: int) -> int:
        h_dist = 0
        while x or y:
            if (x & 1) != (y & 1):
                h_dist += 1
            x = x >> 1
            y = y >> 1
        return h_dist

Problem solution in Java.

class Solution {
    public int hammingDistance(int x, int y) {
        String xout="",yout="";
          int binaryx[] = new int[31],binaryy[] = new int[31];    
        int cntx=0,cnty=0,count=0;
        while(x>0){
        binaryx[cntx++]=x%2;
            x/=2;
        }
        while(y>0){
       binaryy[cnty++]=y%2;
            y/=2;
        }
         for(int i=0;i<31;i++){
            if(binaryx[i]!=binaryy[i])
                count++;
        }
           return count;
    }
}

Problem solution in C++.

class Solution {
public:
    int hammingDistance(int x, int y) {
        int z = x xor y;
        int ans = 0;
        while (z){
            z -= z & (-z);   
            ans ++;
        }
        return ans;
    }
};

Problem solution in C.

int hammingDistance(int x, int y) {
    int count = 0;
    while(x != 0 || y != 0) {
        if( (x&1) != (y&1))
            count++;
        x >>= 1;
        y >>= 1;
    }
    return count;
}

coding problems solutions

Post navigation

Previous post
Next post

Pages

  • About US
  • Contact US
  • Privacy Policy

Programing Practice

  • C Programs
  • java Programs

HackerRank Solutions

  • C
  • C++
  • Java
  • Python
  • Algorithm

Other

  • Leetcode Solutions
  • Interview Preparation

Programming Tutorials

  • DSA
  • C

CS Subjects

  • Digital Communication
  • Human Values
  • Internet Of Things
  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2025 Programmingoneonone | WordPress Theme by SuperbThemes