考虑数194声明为类型 INT 是否有可能得到它的数字的排列像其他有效的整数? 编号:194 419 INT 491 INT 914 INT 941 INT
Consider number 194 declared as type int Is it possible to obtain it's digits permutations like other ints efficiently? Number: 194 419 int 491 int 914 int 941 int
我现在用的是next_permutation但它仅适用于数组。所以,我认为这将是不明智的INT转换为int数组(?!),然后得到排列为一个数组,并将其转换到它。
I am using the next_permutation however it only works with arrays. So I thought it wouldn't be wise to convert int to an int array (?!) then obtain the permutation as an array and convert it to it.
有什么建议?
置换的数字基本上是一个字符串操作,而不是一个(简单)的数学运算。转换到一个数组(字符串),然后用 next_permutation()
听起来不是试图数学上做更明智。
Permuting the digits is basically a string-operation, not a (simple) mathematical operation. Converting to an array (string) and then using next_permutation()
sounds more sensible than trying to do it mathematically.
下面是数学版 - 没有保存的中间值:
Here's the mathematical version - without intermediate values saved:
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
使用中间值,这是一个比较容易看到发生了什么事情(除了我通过产生不同硼
分配 F
这个时候)。
With intermediate values, it's a little easier to see what's going on (except that I generated different assignments for b
through f
this time).
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位数,其中该不会。
Use the next_permutation()
mechanism; it will generalize to 4-digit and 5-digit and N-digit numbers where this will not.