力扣官方题解中有一个比较有趣的优化:

链接:https://leetcode-cn.com/problems/er-jin-zhi-zhong-1de-ge-shu-lcof/solution/er-jin-zhi-zhong-1de-ge-shu-by-leetcode-50bb1/
图片说明

public class Solution {
    public int NumberOf1(int n) {
        int res = 0;
        while (n != 0) {
            n &= n - 1;
            res++;
        }

        return res;
    }
}

时间复杂度:o(logn)