一个整数二进制中1的个数

方法一:

思路:如果一个数与1作与运算则可以发现该数最后一位数为1,否则为0.
按照此思路可以有以下代码:

 1 #include <iostream>
 2   using namespace std;
 3 
 4   int main()
 5   {
 6 
 7       int n = 0;
 8       cout << "输入一个数";
 9       cin >> n;
10       int count = 0;
11       while (n)
12  {
13 
14       if (n & 1)
15       {
16           count++;
17       }
18       n >>= 1;
19   }
20       cout << "1的个数为"<<count<<endl;
21       return 0;
22   }

这里写图片描述

但是此方法存在缺陷如果输入的数为负数则会无限死循环

方法二:

首先把n与1做与运算,判断n的最低位是不是为1。接着把1左移一位得到2,再和n做与运算,就能判断n的次低位是不是1….这样反复左移,每次能判断n的其中一位是不是1.这个解法中循环的次数等于整数二进制的位数,32位的整数需要循环32次

 1 #include <iostream>
 2   using namespace std;
 3 
 4   int main()
 5   {
 6 
 7       int n = 0;
 8       int key = 1;
 9       cout << "输入一个数";
10       cin >> n;
11       int count = 0;
12       while (key)
13  {
14 
15       if (n & key)
16       {
17           count++;
18       }
19       key <<= 1;
20   }
21       cout << "1的个数为"<<count<<endl;
22       return 0;
23   }

方法三

思路:把一个整数减去1,再和原整数做与运算,会把该整数最右边一个1变成0,那么一个整数的二进制表示中有
多少个1,就可以进行多少次这样的操作。

 1 #include <iostream>
 2   using namespace std;
 3 
 4   int main()
 5   {
 6 
 7       int n = 0;
 8       cout << "输入一个数";
 9       cin >> n;
10       int count = 0;
11       while (n)
12  {
13           n = ((n - 1)& n);
14           count++;
15 
16   }
17       cout << "1的个数为"<<count<<endl;
18 }

本文结束。

【转载】https://blog.csdn.net/weibo_dm/article/details/80531465

原文地址:https://www.cnblogs.com/yelao/p/12536398.html