如题,常规做法暂不说。
妙解:
1、 原理:10···0 -1 = 01···1,a & (a-1) = 00···0
每次操作就把最靠近低位的1变为0
int countOne(int n)
{
int count = 0;
while (n)
{
n &= (n-1);
++count;
}
return count;
}
2、打表
table[key] = result
空间换取时间
如题,常规做法暂不说。
妙解:
1、 原理:10···0 -1 = 01···1,a & (a-1) = 00···0
每次操作就把最靠近低位的1变为0
int countOne(int n)
{
int count = 0;
while (n)
{
n &= (n-1);
++count;
}
return count;
}
table[key] = result
空间换取时间