位运算 n & (n - 1)
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
int n = Integer.parseInt(br.readLine());
int ans = 0;
while (n != 0) {
ans++;
n &= (n - 1);
}
pw.println(ans);
pw.flush();
pw.close();
br.close();
}
}
逐位判断
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
int n = Integer.parseInt(br.readLine());
int ans = 0;
for (int i = 0; i < 32; i++) {
if ((n & (1 << i)) != 0) {
ans++;
}
}
pw.println(ans);
pw.flush();
pw.close();
br.close();
}
}