做法是n&(n-1)。据说还有变态的查表法:http://www.cnblogs.com/graphics/archive/2010/06/21/1752421.html。最后,居然必须用scanf/printf。
#include <cstdio> #include <memory.h> using namespace std; int countOne(int x) { int cnt = 0; while (x != 0) { x &= x - 1; cnt++; } return cnt; } int main() { int n; scanf("%d", &n); while (n--) { int x; scanf("%d", &x); int ans = countOne(x); printf("%d ", ans); } return 0; }