首先出题目的位置表达敬意,呵呵呵
https://leetcode.com/problems/number-of-1-bits/
Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11’ has binary representation 00000000000000000000000000001011, so the function should return 3.
题目:给你一个int,你当unsigned int 来用,然后算出来这个数字的二进制数里面有多少个 “1”
public class Solution {
public int hammingWeight(int n) {
int count = 0;
//将负数位先读出来,然后再连除
if(n<0){
count+=1;
n=n&0x7FFFFFFF;
}
//通用的连除2的方法,不适用与负数
while(n!=0){
if(n%2==1)
count++;
n/=2;
}
return count;
}
}