Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hamming Distance #7

Open
hangzz opened this issue Jun 21, 2017 · 0 comments
Open

Hamming Distance #7

hangzz opened this issue Jun 21, 2017 · 0 comments
Labels

Comments

@hangzz
Copy link
Owner

hangzz commented Jun 21, 2017

Hamming Distance

example

Input: x = 1, y = 4

Output: 2

Explanation:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑

answer

//主要就是几个位操作符
var hammingDistance = function(x, y) {
    var a = x ^ y;
    var count = 0 ;
    while ( a ) {
        if (a & 1){
             count ++;
         }
         a = a >> 1;
    }
    return count;
};

Number Complement

example

Input: 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.

answer

var findComplement = function(num) {
    var l = num.toString(2).length;
    var _num =Math.pow(2,l)-1;
    return num^_num
};

var findComplement = function(num) {
  var mask = ~0;   
  while (mask & num) { 
    mask = mask << 1; 
  } 
  return ~(mask ^ num);    
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant