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.
计算出二进制数中所含‘1’的个数:
C++
class Solution {
public:
int hammingWeight(uint32_t n) {
int count = 0;
uint32_t ss = n;
while(ss!=0){
if(ss%2){
count++;
}
ss /= 2;
}
return count;
}
};
java
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num = in.nextInt();
int count = 0;
while(num!=0){
if(num%2==1){
count++;
}
num /= 2;
}
System.out.println(count);
}
}
import java.util.Scanner;
public class Main {
private static Scanner scanner;
public static void main(String[] args) {
scanner = new Scanner(System.in);
int number = findNumberOf1(scanner.nextInt());
System.out.println(number);
}
public static int findNumberOf1(int num) {
int count = Integer.bitCount(num);
return count;
}
}