位运算统计一个正整数对应二进制数中1的个数

    科技2025-10-27  8

    算法一

    int oneCount(int num){ int count = 0; while(num != 0){ if((num & 1) == 1){ count++; } num >>= 1; //右移一位 } return count; }

    算法二

    int oneCount(int n){ int count = 0; while (n != 0){ n &= n-1; count++; } return count; }
    Processed: 0.010, SQL: 8