Basic C++ code using XOR


  • 0
    S
    class Solution {
    public:
        int hammingDistance(int x, int y) {
            
            int dist = 0, n = int(x ^ y);  //typecasting improves running speed. XOR is used to find bits that are different in x and y. eg. 2 (010) XOR 4(100)                                         = 5 (101)
           
            /* Count the number of 1s and update as dist*/
            while(n){
                
                if (n%2 == 1) dist++; //Check if next bit is 1. If yes, add distance by 1
                n = n/2;              // Update n for the process of finding next bit            
                
            }
            
            return dist;
            
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.