一个整数 假如 123 换成二进制 数一下里面有几个一 设计算法 这是我今天遇到的一个笔试题,那个时候我花了大概五分钟,想到了这么一个算法,我想应该是最高效率的了,但由于紧张,写的时候还是写错了。 我现在把他写上来,看看大家有没有比这个方法更好的。 int Count(int num) { int count = 0; while (true) { if ((num & -num) != 0) count++; else break; num &= num - 1; } return count; } 谢谢adrianx 提供了这个方法: int count(int num) { int count = 0; while (num) { count++; num&=num - 1; } return count; }