数字数字的排列

Permutation of a number's digits

本文关键字:数字 排列      更新时间:2023-10-16

考虑声明为类型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

使用中间值,可以更容易地了解发生了什么(除了这次我为bf生成了不同的赋值)。

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.

除非你在一个缓慢/资源受限的环境中运行,否则我不会试图过度思考这个问题。

编辑:

正如评论中所指出的,这并不能生成所有的排列,要做到这一点,需要在结束时添加另一个步骤,重复该过程,但索引变量的增量会越来越大。