二进制中1的个数
题目描述:https://leetcode-cn.com/problems/er-jin-zhi-zhong-1de-ge-shu-lcof/
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n ) {
int res = 0;
while(n != 0) {
res += n & 1;
n >>>=1;
}
return res;
}
}
数组中数字出现的次数
题目描述:https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof/、
class Solution {
public int[] singleNumbers(int[] nums) {
int ret = 0;
for(int n :nums) {
ret ^= n;
}
int div = 1;
while((div & ret)==0) {
div <<= 1;
}
int a = 0, b = 0;
for(int n : nums) {
if((div & n)!=0) {
a ^= n;
}else {
b ^= n;
}
}
return new int[] {a,b};
}
}