The most natural way C++


  • 0
    E
    // loop solution
    class Solution {
    public:
        int hammingDistance(int x, int y) {
            int diff = x ^ y;
            int count = 0;
            while (diff) {
                count += diff & 1;
                diff >>= 1;
            }
            return count;
        }
    };
    // bit manipulation solution
      i = (i & 0x55555555) + ((i >> 1) & 0x55555555);
      i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
      i = (i & 0x0F0F0F0F) + ((i >> 4) & 0x0F0F0F0F);
      return (i*(0x01010101))>>24;
    

Log in to reply
 

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