801. Number of 1s in binary + lowbit() application

Given a sequence of length n, find the number of 1s in the binary representation of each number in the sequence.

Input format
The first line contains the integer n.

The second line contains n integers representing the entire sequence.

Output Format
One line contains n integers, where the ith number represents the number of 1s in the binary representation of the ith number in the sequence.

Data range
1≤n≤100000, 0≤The
value of the element in the sequence≤109
Input example:
5
1 2 3 4 5Output
example:
1 1 2 1 2


#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int a[N];

int lowbit(int x)
{
    
    
    return x & -x;
}

int main()
{
    
    
    int n; 
    cin >> n;
    
    int t;
    while(n--) {
    
    
        cin >> t;
        int res = 0;
        while(t) t -= lowbit(t), res ++; //每次减去t的最后一位1
        cout << res << " ";
    }
    
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324134403&siteId=291194637