比较数字并查找具有相同数字的数字

Comparing digits and finding numbers with same digits

本文关键字:数字 查找 比较      更新时间:2023-10-16

这是我的问题。程序需要打印出m到n之间的数字,这些数字有不同的位数。例如:m=97,n=104;输出:5.我似乎对比较数字和找到检查是否有两个相同数字的方法有问题。以下是我迄今为止写的内容:

enter code here
#include <iostream>
using namespace std;
int main()
{
    int m, n;
    cout << "m=";
    cin >> m;
    cout << "n=";
    cin >> n;
    for (int i = m; i <=n; ++i)
    {
        if (i >= m && i <= n)
        {
            while (i > 0)
            {
                m=i%=10;
                i/= 10; 
                cout << m;
            }
        }
    }
    system("pause");
    return 0;
}

如果你能给我一个最简单的解决方案。提前感谢

最好的方法是将其分解为两部分。主要部分负责递增数字集(如果变量是整数,这是最简单的),第二部分是比较数字的每个部分,看看一个数字是否重复了(最好是作为字符串)。

因此,首先我将定义负责确定值是否具有所有不同数字的方法:

bool hasDistinctDigits(int m) {
    string number = to_string(m);
    for (string::size_type i = 0; i < number.size(); i++) {
        for (string::size_type j = i + 1; j < number.size(); j++) {
            if (number[i] == number[j]) return false;
        }
    }
    return true;
}

这应该很容易理解。首先,我们需要将数字转换为字符串。然后,我们使用2个循环来确定一个字符是否在较高的索引中重复。例如,对于数字102,它将比较以下集合:{1,0}、{1、2}、{0,2}

然后在主函数中,我会这样称呼它:

int main()
{
    int m, n, matched = 0;
    cout << "m=";
    cin >> m;
    cout << "n=";
    cin >> n;
    for (int current = m; current <= n; ++current){
        if (hasDistinctDigits(current)) {
            cout << current << " is distinct" << endl;
            matched++;
        }
    }
    cout << "Total Matched: " << matched << endl;
    system("pause");
    return 0;
}