本文共 508 字,大约阅读时间需要 1 分钟。
关于负数的自己没想出来,这是书中的两种算法,关于位运算的知识还是得要学习一个啊。。。
Solution1:class Solution { public: int NumberOf1(int n) { int count=0; unsigned int flag=1; while(flag){ if(n&flag) count++; flag=flag<<1; } return count; }};
Solution2:
class Solution { public: int NumberOf1(int n) { int count=0; while(n){ ++count; n=(n-1)&n; } return count; }};
转载地址:http://qthdb.baihongyu.com/