题目描述:给定两个长度相等的字符串,分别为答案字符串和猜测字符串(只含数字0-9),编写程序判断猜测的字符串中数字位置和数值均与答案字符串匹配的为'Bulls”,数字位置不匹配但数值匹配的为'Cows”,最终输出'Bulls”和'Cows”的数量。
思路:遍历两个字符串,分别统计其中相同位置数字相同的次数和数值相同但位置不同的次数即可。
具体实现见代码:
#include
#include
int main()
{
char answer[101], guess[101];
int a_len, b_len, bulls = 0, cows = 0;
scanf("%s%s", answer, guess);
a_len = strlen(answer);
b_len = strlen(guess);
if (a_len != b_len)
{
printf("两个字符串长度不等!\n");
return 0;
}
for (int i = 0; i < a_len; i++)
{
if (answer[i] == guess[i])
{
bulls++;
}
else
{
for (int j = 0; j < b_len; j++)
{
if (j != i && answer[i] == guess[j])
{
cows++;
break;
}
}
}
}
printf("Bulls: %d\nCows: %d", bulls, cows);
return 0;
}
上一篇:BullsandCows-turningsimplecodeintofunctions
下一篇:Bulls队列的性能和可扩展性:Queue.add()、Queue.getJob(jobId)、Job.remove()