方法一
用暴力枚举法枚举出二进制所有的情况,化为十进制数存放在一个数组中,
然后再去枚举三进制所有的情况,化为十进制一一去和数组中的元素去匹配,如果相等就说明找到了答案,结束程序
1.将m进制的数转为十进制
int get(char* a, int m)
{
int ret = 0;
int len = strlen(a);
for (int i = 0; i < len; i++)
{
ret = ret * m + (a[i]-'0');
}
return ret;
}
2.去数组中找相等的数
int find(int* arr, int a,int len1)
{
for (int i = 0; i < len1; i++)
{
if (a == arr[i])
return 1;
}
return 0;
}
3.完整代码
#include
#include
#include
int get(char* a, int m)
{
int ret = 0;
int len = strlen(a);
for (int i = 0; i < len; i++)
{
ret = ret * m + (a[i]-'0');
}
return ret;
}
int find(int* arr, int a,int len1)
{
for (int i = 0; i < len1; i++)
{
if (a == arr[i])
return 1;
}
return 0;
}
int main()
{
char a[11], b[11];
scanf("%s", a);
scanf("%s", b);
int len1 = strlen(a);
int len2 = strlen(b);
int* ret1 = (int*)malloc(sizeof(int) * len1);
for (int i = 0; i < len1; i++)
{
a[i] ^= 1;
ret1[i] = get(a, 2);
a[i] ^= 1;
}
int p = 0;
for (int i = 0; i < len2; i++)
{
char t = b[i];
for (int j = 0; j < 3; j++)
{
b[i] = j + '0';
int c = get(b, 3);
if (find(ret1, c,len1) == 1)
{
printf("%d",c);
return 0;
}
b[i] = t;
}
}
return 0;
}
方法二
枚举二进制的所有情况,化为三进制后,去和b比较,假如仅有一位不相同,则说明该情况就是正确答案,程序结束
- 二进制转化为十进制
int get(char* a, int m)
{
int ret = 0;
int len = strlen(a);
for (int i = 0; i < len; i++)
{
ret = ret * m + (a[i] - '0');
}
return ret;
}
2.二进制转化为三进制
char* cp(char* a, int m)
{
char* arr = (char*)malloc(sizeof(char) * 10);
int temp = get(a, m);
int i = 0;
while (temp)
{
arr[i] = temp % 3 + '0';
temp /= 3;
i++;
}
arr[i] = '\0';
for (int j = 0; j < i / 2; j++)
{
char t = arr[j];
arr[j] = arr[i - j - 1];
arr[i - j - 1] = t;
}
return arr;
}
3.统计每位不一样的个数
int count(char* a, char* b)
{
int len1 = strlen(a);
int len2 = strlen(b);
if (len1 != len2)
return 0;
int count = 0;
while (len2 >= 0 && len1 >= 0)
{
if (a[len1] != b[len2])
count++;
len1--;
len2--;
}
return count;
}
4.完整代码
#include
#include
#include
//二转十
int get(char* a, int m)
{
int ret = 0;
int len = strlen(a);
for (int i = 0; i < len; i++)
{
ret = ret * m + (a[i] - '0');
}
return ret;
}
//二转三
char* cp(char* a, int m)
{
char* arr = (char*)malloc(sizeof(char) * 10);
int temp = get(a, m);
int i = 0;
while (temp)
{
arr[i] = temp % 3 + '0';
temp /= 3;
i++;
}
arr[i] = '\0';
for (int j = 0; j < i / 2; j++)
{
char t = arr[j];
arr[j] = arr[i - j - 1];
arr[i - j - 1] = t;
}
return arr;
}
int count(char* a, char* b)
{
int len1 = strlen(a);
int len2 = strlen(b);
if (len1 != len2)
return 0;
int count = 0;
while (len2 >= 0 && len1 >= 0)
{
if (a[len1] != b[len2])
count++;
len1--;
len2--;
}
return count;
}
int main()
{
char a[30], b[30];
scanf("%s", a);
scanf("%s", b);
int len1 = strlen(a);
int len2 = strlen(b);
int* ret1 = (int*)malloc(sizeof(int) * len1);
for (int i = 0; i < len1; i++)
{
a[i] ^= 1;
int t = count(b, cp(a, 2));
if (t == 1)
{
printf("%d", get(a, 2));
return 0;
}
a[i] ^= 1;
}
}