如果您指的是数字的字符(例如 1927 和 9721),则(至少)有几种方法。
如果允许排序,一种方法是简单地sprintf
将它们放入两个缓冲区,对缓冲区中的字符进行排序,然后查看字符串是否相等。
然而,鉴于您的愿望not对数字进行排序,另一种选择是建立一个十元素数组,所有元素最初设置为零,然后处理第一个数字中的每个数字,递增相关元素。
然后对第二个数字执行相同的操作,但递减。
如果最后仍然全为零,则这些数字是彼此的排列。
这是有效的,因为它是O(n)
算法其中n
是两个数字的位数。这种野兽的伪代码类似于:
def arePermutations (num1, num2):
create array count, ten elements, all zero.
for each digit in num1:
increment count[digit]
for each digit in num2:
decrement count[digit]
for each item in count:
if item is non-zero:
return false
return true
在 C 语言中,以下完整程序说明了如何完成此操作:
#include <stdio.h>
#include <stdlib.h>
#define FALSE (1==0)
#define TRUE (1==1)
int hasSameDigits (long num1, long num2) {
int digits[10];
int i;
for (i = 0; i < 10; i++) // Init all counts to zero.
digits[i] = 0;
while (num1 != 0) { // Process all digits.
digits[num1%10]++; // Increment for least significant digit.
num1 /= 10; // Get next digit in sequence.
}
while (num2 != 0) { // Same for num2 except decrement.
digits[num2%10]--;
num2 /= 10;
}
for (i = 0; i < 10; i++)
if (digits[i] != 0) // Any count different, not a permutation.
return FALSE;
return TRUE; // All count identical, was a permutation.
}
int main (int c, char *v[]) {
long v1, v2;
if (c != 3) {
printf ("Usage: %s <number1> <number2>\n", v[0]);
return 1;
}
v1 = atol (v[1]);
v2 = atol (v[2]);
if (hasSameDigits (v1, v2)) {
printf ("%d and %d are permutations\n", v1, v2);
} else {
printf ("%d and %d are not permutations\n", v1, v2);
}
return 0;
}
只需向其传递两个(正)数字,并假设它们适合long
,它会告诉您它们是否具有相同的位数。