Skip to content

M1680.连接连续二进制数字

bit manipulation, https://leetcode.cn/problems/concatenation-of-consecutive-binary-numbers/

cpp
#include <iostream>
#include <numeric>
using namespace std;

class Solution
{
public:
    int concatenatedBinary(int n)
    {
        constexpr int MOD = 1000000007;
        long long res = 0;
        for (int i = 1; i <= n; ++i)
        {
            int w = bit_width((uint32_t)i);
            res = (res << w | i) % MOD;
        }
        return res;
    }
};

int main()
{
    cin.tie(nullptr)->sync_with_stdio(false);

    Solution sol;
    int n = 12;
    cout << sol.concatenatedBinary(n) << '\n';
    return 0;
}

共用时5min