数字数字的排列
Permutation of a number's digits
考虑声明为类型int的数字194有可能像其他int一样有效地获得它的数字排列吗
编号:194
419int
491int
914int
941int
我使用的是next_placement,但它只适用于数组。所以我认为将int转换为int数组(?!),然后获得作为数组的排列并将其转换为它是不明智的。
有什么建议吗?
排列数字基本上是一种字符串运算,而不是(简单的)数学运算。转换为一个数组(字符串),然后使用next_permutation()
听起来比尝试用数学方法更明智。
这是数学版本-不保存中间值:
int a = 194;
int b = (a / 100) * 100 + (a % 10) * 10 + ((a / 10) % 10) * 1; // 149
int c = (a % 10) * 100 + ((a / 10) % 10) * 10 + (a / 100) * 1; // 491
int d = (a % 10) * 100 + (a / 100) * 10 + ((a / 10) % 10) * 1; // 419
int e = ((a / 10) % 10) * 100 + (a / 100) * 10 + (a % 10) * 1; // 914
int f = ((a / 10) % 10) * 100 + (a % 10) * 10 + (a / 100) * 1; // 941
使用中间值,可以更容易地了解发生了什么(除了这次我为b
到f
生成了不同的赋值)。
int a = 194;
int d1 = a / 100;
int d2 = (a / 10) % 10;
int d3 = a % 10;
int a = d1 * 100 + d2 * 10 + d3 * 1; // 194
int b = d1 * 100 + d3 * 10 + d2 * 1; // 149
int c = d2 * 100 + d1 * 10 + d3 * 1; // 914
int d = d2 * 100 + d3 * 10 + d1 * 1; // 941
int e = d3 * 100 + d1 * 10 + d2 * 1; // 419
int f = d3 * 100 + d2 * 10 + d1 * 1; // 491
使用next_permutation()
机制;它将推广到4位数、5位数和N位数,而这不会。
您首先必须提取每个小数位的值:要么将其转换为字符数组(itoa()
),要么编写一个小的for循环,将数字除以10的幂。一旦你把数字分开,你就可以写一个循环来生成排列。
获取十进制数字的排列需要将数字作为十进制进行交互,因此2次幂运算在这里可能没有多大帮助。
我的建议是:
1. Convert number to string
2. Set up the string as a circular buffer
3. Step through the buffer progressively (each increment of the index into the circular buffer will give you one permutation)
4. Reconstruct the number from the "new" arrangement of the characters representing the digits
5. Repeat for the length of the string.
除非你在一个缓慢/资源受限的环境中运行,否则我不会试图过度思考这个问题。
编辑:
正如评论中所指出的,这并不能生成所有的排列,要做到这一点,需要在结束时添加另一个步骤,重复该过程,但索引变量的增量会越来越大。
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 为什么不;名字在地图上是按顺序排列的吗
- 如何用数字处理log(0)
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 如何在不使用 C++ 中的数组或函数的情况下查找 N 位数字的所有排列
- 最大数量.给定一个非负整数列表,排列它们以使它们形成最大的数字
- 使用指针重新排列数组中的数字
- 如何生成没有两个相邻连续数字的排列
- 增量数字更改循环?(所有排列)
- 所有排列,并找到最小数字的 c++
- N个整数与K对数字有多少个不能相邻的排列?
- 给定数字的排列和组合
- 数字数字的排列
- 如何用数字排列字符串
- 在给定N-1个约束的情况下,计算小于整数N的数字的可能排列数
- 如何用C++编写一个程序,该程序从输入中接收10个数字并检查这些数字是否按升序排列
- 排列数字的麻烦