Advertisement
jasonpogi1669

Count the No. of Set Bits of N using C++

Jan 27th, 2022
1,061
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.26 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int main() {
  6.     int n;
  7.     cin >> n;
  8.     int res = 0;
  9.     for (int bit = 31; bit >= 0; bit--) {
  10.         // don't forget to type cast into boolean
  11.         res += ((bool) (n & (1 << bit)));
  12.     }
  13.     cout << res << '\n';
  14.     return 0;
  15. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement