我在让这段代码按照我想要的方式工作时遇到了问题。任务是编写一个程序,打印输入数字 n (1 <= n <= 9) 的数字 1 到 n 的排列所获得的所有数字。该程序还应该打印出有多少这样的数字。我做了一个 for 循环来获取 n 的阶乘,这样我就可以获得排列的数量,并且我将所有从 1 到 n 的数字组合成一个整数,因为我认为应该有一种方法可以那样找到排列。所以我的问题是如何找到这些排列?
#include <iostream>
using namespace std;
int main(){
int n;
int j;
int r=0;
int t=1;
double f=1;
cin>>n;
for(int p=1;p<=n-1;p++){
t=t*10;
}
int u=t;
//calculates the factorial of n
for(int o=1;o<=n;o++){
f=f*o;
}
//writes numbers from 1 to n into an integer
for(int d=1;d<=n;d++){
j=d*u;
r=r+j;
u=u/10;
}
}
最佳答案
首先,将数字读入字符串。如果要确保格式正确,您可以将其读入一个整数,然后将其写入一个字符串:
int number;
if (!(std::cin >> number)) {
// Failure to read number. Do some diagnostic.
throw std::runtime_error("invalid number");
}
// Number read successfully. Write it to a string.
std::string s = std::to_string(number);
第一个排列是所有数字的排序排列。使用 std::sort
很容易获得这一点。
std::sort(s.begin(), s.end());
最后,使用 std::next_permutation
获得其他排列。一旦获得最后一个,它将返回 false
并退出循环。
int n{0};
do {
++n;
std::cout << s << '\n';
} while (std::next_permutation(s.begin(), s.end()));
std::cout << "Number of permutations: " << n;
关于c++ - 如何在不使用 C++ 中的数组或函数的情况下查找 n 位数字的所有排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52449985/