http://cloj.ddns.net/problem/tongbit

28/11/2023
Code
#include <bits/stdc++.h>
#define int long long 
#define pb push_back
#define fi first
#define se second
#define pii pair<long long, long long>
#define endl "\n"
#define FILE(A) freopen(A".INP", "r", stdin); freopen(A".OUT", "w", stdout)
#define TIME (1.0 * clock() / CLOCKS_PER_SEC)

using namespace std;

const int N = 2 * 1e5 + 5;
const int mod = 1e9+7;
const int oo = 1e16;
const int base = 31;

int n, res=0;


int cntBit(int n) {
    int ans = 0;
    for (int mask = 0;mask <= n;mask++) {
        ans += __builtin_popcountll(mask);
    }
    return ans;
}

void solve(int n) {
        int left=0, right=0;
        bitset<64> bit = n;
        for (int i=0;i < 20;i++) {
            left = left | (bit[i] << i);
        }
        right = (bit.to_ullong() >> 20);
        int old_left = left;
        left = left | (1ll<<20);
        int cntRight = cntBit(right-1);
        res = cntBit((1<<20)-1)*(right)*1ll + cntRight*((1<<20))*1ll;
        for (int mask=0;mask <= old_left; mask++) {
            res += (__builtin_popcountll(mask)) + (__builtin_popcountll(right));
        }
        cout << res << endl;
}

signed main(){
    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
    
    cin >> n;
    solve(n);

    return 0;
}

// Nguyen Minh Hieu - 2008 - Gia Lai
// https://hieuhfgr.pythonanywhere.com/