top1编程
← 返回题目
题解

【基础】既生瑜,何生亮!

2 条题解

  • 0
    @ 2026-10-25 15:41:13

    1. 解题思路

    从 x 到 y 枚举每个整数;只保留平方在 1000000 到 9999999 的数,用 10 个布尔标记逐位记录数字,全部 7 位没有重复就输出该整数。

    2. 坑点和注意事项

    题面输入格式误写一个整数,但描述和样例都是 x、y 两个端点,沿用原读入方式。每个新平方都清空标记,数字 0 也需检查;先通过 7 位数门槛,故无重复时不必再统计 7 种数字。

    3. 复杂度

    • 时间复杂度:O(y - x + 1),每个候选至多检查 7 位
    • 空间复杂度:O(1),10 个固定标记
    /*
    思路:依次枚举 x 到 y 中的数,先检查平方是否为 7 位数,再检查各位数字是否重复。
    关键:7 位数必须在 1000000 到 9999999 之间;用下标 0 到 9 的标记数组记录数字。
    坑点:每次检查新的平方都要清空标记;数字 0 也需要记录,出现重复数字就立即停止。
    数据类型:先转成 long long 再相乘,平方和拆位过程都使用 long long。
    时间复杂度:O(y - x + 1),每个符合位数条件的平方至多检查 7 位。
    空间复杂度:O(1),标记数组固定为 10 个元素。
    */
    #include<bits/stdc++.h>
    using namespace std;
    int main()
    {
        int x, y;
        cin >> x >> y;
        for (int n = x; n <= y; n++)
        {
            long long square = (long long)n * n;
            // 先限制为 7 位数,后面只需要判断是否有重复数字。
            if (square < 1000000 || square > 9999999)
            {
                continue;
            }
            bool digits[10] = {};
            long long temp = square;
            bool unique = true;
            while (temp > 0)
            {
                int digit = temp % 10;
                if (digits[digit])
                {
                    unique = false;
                    break;
                }
                digits[digit] = true;
                temp /= 10;
            }
            if (unique)
            {
                cout << n << endl;
            }
        }
        return 0;
    }
    
    • 0
      @ 2026-7-30 1:07:31

      解题思路

      按照题目给出的规则读入数据,逐步计算结果并输出。

      参考代码

      // 这道题的做法:先读入题目给出的数据,再用简单的循环和判断完成要求。
      #include <iostream>
      #include <set>
      using namespace std;
      
      int main() {
          int x, y;
          cin >> x >> y;
          
          for (int n = x; n <= y; n++) {
              long long square = (long long)n * n;
              
              // 检查平方是否为7位数
              if (square < 1000000 || square > 9999999) {
                  continue;
              }
              
              // 检查7个数字是否互不相同
              set<int> digits;
              long long temp = square;
              bool unique = true;
              
              while (temp > 0) {
                  int digit = temp % 10;
                  if (digits.count(digit)) {
                      unique = false;
                      break;
                  }
                  digits.insert(digit);
                  temp /= 10;
              }
              
              if (unique && digits.size() == 7) {
                  cout << n << endl;
              }
          }
          
          return 0;
      }
      

      复杂度

      代码只使用了简单变量、循环和判断。若循环检查了 n 个数据,时间复杂度通常为 O(n);没有开辟与输入规模相关的额外数组时,空间复杂度为 O(1)。

      • 1