Skip to content
Programmingoneonone
Programmingoneonone
  • Engineering Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
    • 100+ C++ Programs
  • Solutions
    • HackerRank
      • Algorithms Solutions
      • C solutions
      • C++ solutions
      • Java solutions
      • Python solutions
    • Leetcode Solutions
    • HackerEarth Solutions
  • Work with US
Programmingoneonone
Programmingoneonone

Leetcode Hamming Distance problem solution

YASH PAL, 31 July 202422 January 2026

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

Leetcode Hamming Distance 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

Hamming Distance 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 Leetcode Problems Solutions Leetcode

Post navigation

Previous post
Next post

Leave a Reply

Your email address will not be published. Required fields are marked *

Programmingoneonone

We at Programmingoneonone, also known as Programming101 is a learning hub of programming and other related stuff. We provide free learning tutorials/articles related to programming and other technical stuff to people who are eager to learn about it.

Pages

  • About US
  • Contact US
  • Privacy Policy

Practice

  • Java
  • C++
  • C

Follow US

  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2026 Programmingoneonone | WordPress Theme by SuperbThemes