Topic Overview
Implement a function, asks an integer, the number of output binary number corresponding to the number of 1 in. 9 example is represented as a binary 1001, then the input 9, then, the screen printing 2
Solving Method 1
size_t numberOf1(int value)
{
int count = 0;
while(value){
if(value & 0x01){
++count;
}
value = value >> 1;
}
return count;
}
Analysis:
One problem with this method encountered is negative, a -1 if passed, what would happen?
Yes, infinite loop , we need to improve.
Solving Method 2
//防止出现负数导致无线循环
size_t numberOf1(int value)
{
int count = 0;
for(size_t i = 0; i < 32; ++i){
if(value % 1){
++count;
}
value = value >> 1;
}
return count;
}
Analysis:
negative number may be calculated, but every time cycle 32 times, can not be optimized a little bit?
Solving Method 3
//当一个数与上比自己小1的数,那么该数最后一个1会被置为0
size_t numberOf1(int value)
{
int count = 0;
while(value){
++count;
value = (value - 1) & value;
}
return count;
}
----------------------------------------
Disclaimer: This article is CSDN blogger "Hao Hao Song "of the original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
Original link: https://blog.csdn.net/qq_31828515/article/details/62041384
------------------------------ ----------