力扣官方题解中有一个比较有趣的优化:
public class Solution { public int NumberOf1(int n) { int res = 0; while (n != 0) { n &= n - 1; res++; } return res; } }
public class Solution { public int NumberOf1(int n) { int res = 0; while (n != 0) { n &= n - 1; res++; } return res; } }