1 条题解

  • 0
    @ 2055-10-31 0:14:07

    【例49.1】回文平方数

    解题思路

    枚举十进制1~300,用除B取余法转出i与i²的B进制字符串。平方串与其反转相等时输出这两串。

    正确性说明

    按顺序完成所述运算后,每个输入元素都被处理在相应位置或统计项中。保存的中间状态与已处理数据对应,最终输出与题目定义一致。

    易错点

    判断回文的是平方的B进制表示,输出的原数也要转B进制。

    复杂度

    300个数,每数D位,时间O(300D),空间O(D)。

    参考代码(C++11)

    #include <bits/stdc++.h>
    using namespace std;
    
    string base(int x, int b) {
        string s;
        do {
            s += "0123456789ABCDEFGHIJ"[x % b];
            x /= b;
        } while (x);
        reverse(s.begin(), s.end());
        return s;
    }
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        int B;
        cin >> B;
        for (int x = 1; x <= 300; x++) {
            string s = base(x * x, B), t = s;
            reverse(t.begin(), t.end());
            if (s == t)
                cout << base(x, B) << " " << s << "\n";
        }
        return 0;
    }
    
    • 1

    信息

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