Question 1. Hamming distance
- Hamming Distance - # of bits are difference from each others
public class Solution {
public int hammingDistance(int x, int y) {
int cnt = 0;
int diff = x^y;
while(diff != 0){
diff = diff & (diff -1);
cnt++;
}
return cnt;
}
}
Question 2. Hamming weight
- Hamming weight- # of bits of given number
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int cnt = 0;
while(n != 0){
n = n & (n-1);
cnt++;
}
return cnt;
}
}
Question 3. Number Complement
- Update version
public class Solution {
public int findComplement(int num) {
return ~num & ((Integer.highestOneBit(num) << 1) - 1);
}
}
public class Solution {
public int findComplement(int num) {
int mask = 1;
while(mask < num){
mask = mask<<1;
}
return ~num & (mask-1);
}
}
Question 4. power of 4
public class Solution {
public boolean isPowerOfFour(int num) {
return (num > 0) && ( (num & (num-1) )== 0) && ((num & 0x55555555) != 0) ;
}
}
/**
* Hexademical representation
* a: 10 , b : 11 , c : 12, d : 13, e : 14, f : 15
* 0xa20 -> 1010 0010 0000
*/
Question 5. find single number
*Given an array of integers, every element appears twice except for one. Find that single one.
public class Solution {
public int singleNumber(int[] nums) {
int res = 0;
int i = 0;
while(i < nums.length){
res^=nums[i];
i++;
}
return res;
}
}
/**
* N ^ 0 = N
* N ^ N = 0
*/