我有一个函数 repsEqual
,它接受一个数组和一个整数,如果数组仅包含出现在相同数字中的相同顺序的数字,则返回 1。否则返回 0。
int repsEqual(int a[], int len, int n)
如果 a
是 {3,2,0,5,3}
并且 n
是 32053
返回1
因为该数组仅包含数字的数字,其顺序与数字中的顺序相同。
如果a
是{0,3,2,0,5,3}
并且n
是32053
返回 1
;我们可以忽略前导零。
我试过这样
int repsEqual(int a[], int len, int n)
{
int len = sizeof(a)/sizeof(a[0]);
//storing elements in array
for(int i=0;i<len;i++)
{
scanf("%d", &a[i]); //eg storing:3 2 0 5 3
}
//asking user integer number and storing in next array
scanf("%d",&a2[num]);//eg 32053
}
现在我需要检查 a2
元素的顺序是否与 a1
相同,但不知道如何开始。
这就是你想要的
int repsEqual(int a[], int len, int n)
{
for (int i = 0; i < len; i++)
{
if (a[len - i - 1] == n % 10)
n /= 10;
else
return 0;
}
//For cases where your number-length is longer than your array length
if (n != 0) return 0;
return 1;
}
首先你有你的数组,比如a[5] = { 5, 2, 3, 1, 4}
基本上我所做的是从头到尾循环数组,即 a[len - i - 1]
然后我用 n
的最后一个字符检查它那就是 n%10
因此以 n = 52314 为例,第一个 if 语句 检查是否 (52314 % 10) 是 4 等于 a[4] 也是 4嗯
如果 2 个字符匹配,则循环首先通过删除 n 的最后一个字符继续:52314/10 = 5231。
下一个循环将检查 5231 % 10 和 a[3]
else循环中途中断返回0表示发现不匹配
最后检查完数组中的所有字符,没有发现不匹配,返回1,作为模式匹配
Note: a function should only does what its name says
In your case, check if an array and an integer have the same pattern
User input should be put outside somewhere else, after you have the inputs (the array, the len, and n) you then pass-in to repsEqual
for checking