StarryCoding 算法小白周赛2 题解与代码(含视频题解)-B:1的数量

时间:2024-05-05 09:00:35

由于数的范围很小,假如这个数合法,我们直接从此数 + 1 +1 +1开始枚举,直到合法为止

最坏情况下时间复杂度为 O ( T n / 2 ) O(Tn/2) O(Tn/2)

#include<bits/stdc++.h>
#define int long long
#define inf 0x3f3f3f3f3f3f3f
const int N = 2e5 + 10;
const int M = 15;
const int mod = 998244353;
using namespace std;
typedef pair<int, int>p;
typedef long long ll;

int a(int x)
{
    int res = 0;
    while (x)
    {
        if (x & 1)res++;
        x >>= 1;
    }
    return res;
}

signed main()
{
    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    int T = 1;
    cin >> T;
    while (T--)
    {
        int n;
        cin >> n;

        if (a(n)<=2)
        {
            n++;
            while (a(n) >= 3)n++;
            cout << n << endl;
        }
        else
        {
            cout << a(n) << endl;
        }
    }
}