题目192:
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as theHamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011
, so the function should return 3.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
//给定一个整数(可能为正负数),求其二进制中1的个数。
//思路:如果为负数的话,直接求其正数的二进制,然后+1
int count=0;
while(n!=0){
//关键步骤
// 两个操作数中位都为1,结果才为1,否则结果为0
count+=(n&1);
//>>表示右移,如果该数为正,则高位补0,若为负数,则高位补1;
//>>>表示无符号右移,也叫逻辑右移,即若该数为正,则高位补0,而若该数为负数,则右移后高位同样补0。
n=n>>>1;
}
return count;
}
}
题目462:
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x
and y
, calculate the Hamming distance.
Note:
0 ≤ x
, y
< 231.
Example:
Input: x = 1, y = 4 Output: 2 Explanation: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ The above arrows point to positions where the corresponding bits are different.
分析:
class Solution {
public int hammingDistance(int x, int y) {
//给定两个数x、y,求x的二进制表达式需要改变多少位才能变成y
//思路:首先对x和y进行异或,之后将异或结果求其中多少个1
int res=x^y;
int count=0;
while(res!=0){
count++;
res=(res-1)&res;
}
return count;
}
}
题目477:
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Now your job is to find the total Hamming distance between all pairs of the given numbers.
Example:
Input: 4, 14, 2 Output: 6 Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just showing the four bits relevant in this case). So the answer will be: HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.
Note:
- Elements of the given array are in the range of
0
to10^9
- Length of the array will not exceed
10^4
.
分析:
class Solution {
public int totalHammingDistance(int[] nums) {
//给定多个数,求所有数其中共需要变化多少位才能相同
//思路:如果数组中k个数在某一位均为1而其他n-k个在该位上不为1,则需要变动k*(n-k)个数才能在某一位相同
//注意:暴力解法每两个单独比,肯定TML。
int count=0;
//对32位范围整数进行遍历
for(int i=0;i<32;i++){
int bitCount=0;
for(int j=0;j<nums.length;j++){
bitCount+=(nums[j]>>i)&1;
}
count+=bitCount*(nums.length-bitCount);
}
return count;
}
}