1 条题解

  • 0
    @ 2074-1-31 15:14:41

    练45.2 异或运算

    解题思路

    枚举x=0~n,直接计算x^(2x)^(3x),结果为0就计数。上界百万,线性枚举足够。

    正确性说明

    计算规则直接来自题目定义。按所述顺序处理时,已完成部分的结果被准确保存在累加量、计数或当前状态中;下一步只加入新增贡献。最终得到完整要求的结果。

    易错点

    ^是按位异或不是乘方;0也属于枚举范围。

    复杂度

    时间 O(n),额外空间 O(1)。

    参考代码(C++11)

    #include <bits/stdc++.h>
    using namespace std;
    
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        int n;
        cin >> n;
        int ans = 0;
        for (int x = 0; x <= n; x++)
            if ((x ^ (2 * x) ^ (3 * x)) == 0)
                ans++;
        cout << ans << "\n";
        return 0;
    }
    
    • 1

    信息

    ID
    313
    时间
    1000ms
    内存
    64MiB
    难度
    进阶
    标签
    递交数
    0
    已通过
    0
    上传者