1. n & n-1

int numOf1(int x) {
    int c = 0;
    while (x) {
        ++c;
        x &= x-1;
    }
    return c;
}

2. 递归

int numOf1(int x) {
    if (!x) return 0;
    return x%2 + numOf1(x/2);
}
posted on 2016-10-16 12:55  未雨愁眸  阅读(149)  评论(0编辑  收藏  举报