记一个C#计算二级制数中有多少个1的方法

public int CountOnesWithBitOperation(int n)
{
    int count = 0;
    while (n != 0)
    {
        n &= (n - 1); // 消除最右边的1
        count++;
    }
    return count;
}
posted @ 2025-11-14 14:35  honyide  阅读(4)  评论(0)    收藏  举报