import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int num = Integer.parseInt(br.readLine().trim());
int count = 0;
while(num != 0){
num &= num - 1;
count ++;
}
System.out.println(count);
}
} import java.util.*;
public class Main {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int res = count2(n);
System.out.println(res);
sc.close();
}
//最多遍历32次 不断看最右边的bit是否为1
public static int count0 (int n) {
int res = 0;
while (n != 0) {
res += n & 1;
n >>>= 1;
}
return res;
}
//不断减去最右边的1
public static int count1 (int n) {
int res = 0;
while (n != 0) {
n -= n & (~n + 1);
res++;
}
return res;
}
//不断抹除掉最右边的1
public static int count2 (int n) {
int res = 0;
while (n != 0) {
res++;
n &= n-1;
}
return res;
}
} 为什么总是报
a.cpp:22: Error: symbol 'LOOP_START' is already defined
a.cpp:26: Error: symbol 'NONZERO_TEST' is already defined
label改成什么都说重复定义!
#include <iostream>
int count(const int n){
int res = 0;
asm(
"push %%rsi\n"
"xor %%eax, %%eax\n"
"jmp NONZERO_TEST\n"
"LOOP_START:"
"mov %%edi, %%esi\n"
"and $1, %%esi\n"
"add %%esi, %%eax\n"
"shr %%edi\n"
"NONZERO_TEST:"
"test %%edi, %%edi\n"
"jne LOOP_START\n"
"pop %%rsi\n"
:"=a"(res)
);
return res;
}
int main(){
using namespace std;
int n;
cin >> n;
cout << count(n) << endl;
return 0;
}