Skip to content
Programmingoneonone
Programmingoneonone
  • CS Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
    • Cybersecurity
  • 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
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 *

CLOSE ADS
CLOSE ADS

Pages

  • About US
  • Contact US
  • Privacy Policy

Follow US

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