How to get /count the number of ones in binary form of a number using BIT Manipulation?
So in this blog, we will see how we can count the number of ones in a number in its binary form.As we know that if we take AND of a number with 1 it will give 0 if the number is 0 and 1 if the number is one.So we will take the AND every time with the LSB of the number and then right-shift the number.
Here is the code of the program in C++. The code starts in the Solve function.
#include <bits/stdc++.h>
using namespace std;
#define int long long int#define F first#define S second#define pb push_back#define si set<int>#define vi vector<int>#define pii pair<int, int>#define vpi vector<pii>#define vpp vector<pair<int, pii>>#define mii map<int, int>#define mpi map<pii, int>#define spi set<pii>#define endl "\n"#define sz(x) ((int)x.size())#define all(p) p.begin(), p.end()#define double long double#define que_max priority_queue<int>#define que_min priority_queue<int, vi, greater<int>>#define bug(...) __f(#__VA_ARGS__, __VA_ARGS__)#define print(a) \ for (auto x : a) \ cout << x << " "; \ cout << endl#define print1(a) \ for (auto x : a) \ cout << x.F << " " << x.S << endl#define print2(a, x, y) \ for (int i = x; i < y; i++) \ cout << a[i] << " "; \ cout << endl
void solve(){
int n; cin >> n; int ans = 0; while (n) { ans += (n & 1); n = n >> 1; //OR What you can do is this
// n = n & (n-1);
// ans++;
} cout<<ans<<endl;}
int32_t main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
clock_t z = clock();
int t = 1; cin >> t; while (t--) solve();
return 0;}
Thank you for reading this.
#include <bits/stdc++.h>
using namespace std;
#define int long long int
#define F first
#define S second
#define pb push_back
#define si set<int>
#define vi vector<int>
#define pii pair<int, int>
#define vpi vector<pii>
#define vpp vector<pair<int, pii>>
#define mii map<int, int>
#define mpi map<pii, int>
#define spi set<pii>
#define endl "\n"
#define sz(x) ((int)x.size())
#define all(p) p.begin(), p.end()
#define double long double
#define que_max priority_queue<int>
#define que_min priority_queue<int, vi, greater<int>>
#define bug(...) __f(#__VA_ARGS__, __VA_ARGS__)
#define print(a) \
for (auto x : a) \
cout << x << " "; \
cout << endl
#define print1(a) \
for (auto x : a) \
cout << x.F << " " << x.S << endl
#define print2(a, x, y) \
for (int i = x; i < y; i++) \
cout << a[i] << " "; \
cout << endl
void solve()
{
int n;
cin >> n;
int ans = 0;
while (n)
{
ans += (n & 1);
n = n >> 1;
//OR What you can do is this
// n = n & (n-1);
// ans++;
}
cout<<ans<<endl;
}
int32_t main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
clock_t z = clock();
int t = 1;
cin >> t;
while (t--)
solve();
return 0;
}
0 Comments
If you have any doubts/suggestion/any query or want to improve this article, you can comment down below and let me know. Will reply to you soon.