Advertisement
tuki2501

bit.cpp

Feb 23rd, 2022
701
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.52 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. typedef long long ll;
  5.  
  6. signed main() {
  7.   cin.tie(0)->sync_with_stdio(0);
  8.   ll n; cin >> n;
  9.   vector<int> a;
  10.   // chuyen n thanh mang nhi phan
  11.   while (n != 0) {
  12.     a.push_back(n % 2);
  13.     n /= 2;
  14.   }
  15.   ll ans = 0;
  16.   // xet tung vi tri i
  17.   for (int i = 0; i < (int) a.size(); i++) {
  18.     // neu vi tri i la bit 1
  19.     if (a[i] == 1) {
  20.       // truong hop khong thay doi (tuc giu nguyen n) thi co 1 bit
  21.       ans += 1;
  22.  
  23.       for (int j = 0; j < (int) a.size(); j++) {
  24.         // minh dem so bit 1 o vi tri i nen khong xet truong hop thay doi bit i
  25.         // thay doi bit thu j tu 1 thanh 0 thi moi thay doi cac bit truoc j duoc
  26.         // nen minh bo qua truong hop a[j] == 0
  27.         if (j == i || a[j] == 0) continue;
  28.  
  29.         // xet truong hop thay doi thay doi bit thu j va j bit dau (0 -> j - 1)
  30.         // neu j > i thi phai tru bot di 1 vi khong thay doi vi tri i
  31.         if (j < i) ans += (1ll << j);
  32.         else ans += (1ll << (j - 1));
  33.       }
  34.     }
  35.     // neu vi tri i la bit 0
  36.     else {
  37.       // minh chi xet nhung vi tri j lon hon i
  38.       // de co the thay doi bit thu i thanh 1
  39.       for (int j = i + 1; j < (int) a.size(); j++) {
  40.         // thay doi bit thu j tu 1 thanh 0 thi moi thay doi cac bit truoc j duoc
  41.         // nen minh bo qua truong hop a[j] == 0
  42.         if (a[j] == 1) {
  43.           // j > i nen phai tru bot di 1 vi khong thay doi vi tri i
  44.           ans += (1ll << (j - 1));
  45.         }
  46.       }
  47.     }
  48.   }
  49.   cout << ans << '\n';
  50. }
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement