方法一:
比較暴力的方法(通過將二進制右移獲得):
int _Count(int x) { int cnt = 0; while(x) { cnt += x&1; x >>= 1; } return cnt; }
方法二:
通過這個數與比他小1的數相與得到:(很神奇的一個方法,手動寫幾個例子就可以看出來了,不過要自己想的話,還是比較費力的)
int _Count(int x) { int cnt = 0; while(x) { x &= (x-1); cnt++; } return cnt; }