求整數n的二進位制數 1的個數,0的個數
阿新 • • 發佈:2019-01-06
#include <iostream>
// 這個只能求正整數的0的個數
int ZeroN(int n)
{
int count = 0;
while(n > 1)
{
if(0 == n%2)
count++;
n >>= 1;
}
return count;
}
// 可正可負,注意,負數是用補碼存的
int OneN(int n)
{
int count = 0;
while(n)
{
count++;
n &= n-1 ;
}
return count;
}
int main(void)
{
int n;
while(std::cin >> n)
{
std::cout <<"ZeorN = " << ZeroN(n) << std::endl;
std::cout <<"OneN = " << OneN(n) << std::endl;
std::cout << std::endl;
}
return 0;
}