AcWing 801. 二進制中1的個數

網址 https://www.acwing.com/solution/AcWing/content/2066/ios

題目描述
給定一個長度爲n的數列,請你求出數列中每一個數的二進制表示中1的個數。算法

算法1
主要是使用位移和 按位與判斷最後一位是不是1ide

int checkNum;
(checkNum &1)
checkNum >>= 1;spa

C++ 代碼code

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 int T;
 6 const int N= 1e6+100;
 7 int arr[N];
 8 
 9 void check(int checkNum)
10 {
11     int count = 0;
12 
13     while(checkNum !=0){
14         if(checkNum &1)
15             count++;
16         checkNum >>= 1;
17     }
18 
19     cout << count << " ";
20 }
21 
22 int main()
23 {
24     cin >> T;
25 
26     int idx = 0; 
27     while(T--){
28         cin >> arr[idx++];        
29     }
30 
31     for(int i =0;i < idx;i++)
32         check(arr[i]);
33 
34     return 0;
35 }
36 
37 
38 做者:defddr
39 連接:https://www.acwing.com/solution/AcWing/content/2066/
40 來源:AcWing
41 著做權歸做者全部。商業轉載請聯繫做者得到受權,非商業轉載請註明出處。
View Code
相關文章
相關標籤/搜索