C++程序在给定范围内查找每个数字都不同的数字
假设我们有两个数字l和r。我们必须找出 x 这个整数,它在 l 和 r 之间(包括两者),x 中的所有数字都不同。
因此,如果输入类似于 l = 211; r = 230,那么输出将是 213。
步骤
为解决此问题,我们将按照以下步骤进行操作:
for initialize k := l, when k <= r, update (increase k by 1), do: h := convert k to string Define one set s for initialize i := 0, when i < size of h, update (increase i by 1), do: insert h[i] into s if size of s is same as size of h, then: return h return "-1"
示例
让我们看看以下实现以加深理解:
#include <bits/stdc++.h>
using namespace std;
string solve(int l, int r) {
for (int k = l; k <= r; k++) {
string h = to_string(k);
set<char> s;
for (int i = 0; i < h.size(); i++)
s.insert(h[i]);
if (s.size() == h.size()) {
return h;
}
}
return "-1";
}
int main() {
int l = 211;
int r = 230;
cout << solve(l, r) << endl;
}输入
211, 230
输出
213
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP