如何在不使用 C++ 中的数组或函数的情况下查找 N 位数字的所有排列
how to find all permutations of an n digit number without using array or function in c++
我在使这段代码按照我想要的方式工作时遇到了问题。任务是编写一个程序,该程序打印通过输入的数字 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;
现场示例
相关文章:
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 如何在不使用 C++ 中的数组或函数的情况下查找 N 位数字的所有排列
- 在无法访问向量的情况下查找迭代器的末尾
- 在不进行排序的情况下查找数组中n个最小值的索引
- 在给定元素在螺旋上的位置的情况下,在二维数组中查找元素
- 在没有查找表的情况下计算大数的位长度
- 如何在给定任意数量的整数的情况下创建一个唯一键?并使用该键存储,然后从地图中查找
- 在没有比较运算符的情况下查找 2 个数字之间的最小值
- 为什么在这种情况下不考虑依赖于参数的查找?
- 我如何在C 中制作算法,以在不重复的情况下查找集合的变化(即n元素,选择k)
- 在给定长度无限循环的情况下,在Collatz猜想中查找起始数的代码
- 在没有字符串或字符帮助的情况下查找数字的反面(例如:2500 reverse 0025)
- 如何在不使用目录的情况下在磁盘上查找文件
- 如何在不使用if语句的情况下查找数组中的最大值和最小值
- 如何在不复制或查找的情况下获取 const 字符串流缓冲区的长度?
- using声明如何减少可用于在没有 ADL 的情况下查找的名称
- 在没有第三方工具/项目的情况下,在 MFC C++发布版本中查找内存泄漏
- 如何在<string>没有 std::string 中介的情况下制作一个支持通过 C 字符串查找的集合?
- C/C++宏,用于在不使用三元运算符的情况下查找两个数字的最大值
- 如何在不遍历内容的情况下查找文件中的字符数