Your code is a bit more complicated than it needs to be.
Just compute a "has a digit" vector for each number (e.g. each element is 1 if the corresponding digit is in the number). This is a histogram/frequency table except that instead of the count of the digits in a number, it's just 0 or 1.
Then, compare the vectors for equality.
Here's some refactored code:
#include <stdio.h>
#include <stdlib.h>
void
count(int x,int *hasdig)
{
int dig;
// handle negative numbers
if (x < 0)
x = -x;
// special case for zero
// NOTE: may not be necessary
#if 1
if (x == 0)
hasdig[0] = 1;
#endif
for (; x != 0; x /= 10) {
dig = x % 10;
hasdig[dig] = 1;
}
}
int
same_digit(int a, int b)
{
int dig_a[10] = { 0 };
int dig_b[10] = { 0 };
int dig;
int same = 1;
count(a,dig_a);
count(b,dig_b);
for (dig = 0; dig < 10; ++dig) {
same = (dig_a[dig] == dig_b[dig]);
if (! same)
break;
}
return same;
}
int
main()
{
int a, b;
scanf("%d", &a);
scanf("%d", &b);
if (same_digit(a, b))
printf("Yes\n");
else
printf("No\n");
return 0;
}
UPDATE:
Also beware UB if either or both numbers is INT_MIN
Yes, -INT_MIN
is still negative :-(
I've come up with an alternate way to deal with it. However, IMO, [almost] any approach seems to be extra work, just to make one special case work. So, I've kept the original [faster/simpler] code above
And, I've added some extra test/debug code.
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int opt_t;
void
count(int x,int *hasdig)
{
int dig;
// handle negative numbers
if (x < 0)
x = -x;
// special case for zero
// NOTE: may not be necessary
#if 1
if (x == 0)
hasdig[0] = 1;
#endif
for (; x != 0; x /= 10) {
dig = x % 10;
// my -INT_MIN fix ...
if (dig < 0)
dig = -dig;
hasdig[dig] = 1;
}
}
int
same_digit(int a, int b)
{
int dig_a[10] = { 0 };
int dig_b[10] = { 0 };
int dig;
int same = 1;
count(a,dig_a);
count(b,dig_b);
for (dig = 0; dig < 10; ++dig) {
same = (dig_a[dig] == dig_b[dig]);
if (! same)
break;
}
return same;
}
void
dotest(int a,int b)
{
printf("a=%d b=%d -- %s\n",
a,b,same_digit(a,b) ? "Yes" : "No");
}
int
main(int argc,char **argv)
{
char *cp;
--argc;
++argv;
for (; argc > 0; --argc, ++argv) {
cp = *argv;
if (*cp != '-')
break;
if ((cp[1] == '-') && (cp[2] == 0)) {
--argc;
++argv;
break;
}
cp += 2;
switch(cp[-1]) {
case 't':
opt_t = ! opt_t;
break;
}
}
do {
int a, b;
if (opt_t) {
dotest(4423,2433);
dotest(INT_MIN,1234678);
dotest(INT_MIN,INT_MIN);
dotest(INT_MAX,INT_MAX);
break;
}
if (argc > 0) {
for (; argc > 0; --argc, ++argv) {
cp = *argv;
if (sscanf(cp,"%d,%d",&a,&b) != 2)
break;
dotest(a,b);
}
break;
}
scanf("%d", &a);
scanf("%d", &b);
dotest(a,b);
} while (0);
return 0;
}