11ms Java solution (no API method used)


  • 0
    W
       public int hammingDistance(int x, int y) {
            if(x == 0 && y ==0) {
                return 0;
            }
            if(x == 0 && y != 0) {
               return getHammingDistance(y);
            }
            if(x != 0 && y == 0) {
               return getHammingDistance(x);
            }
            return getHammingDistance(x ^ y);
        }
        
        public int getHammingDistance(int n) {
            int count =0;
            while(n != 0) {
                n &=n-1;
                count++;
            }
            return count;
        }
    

Log in to reply
 

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