char* user_itoa(int _value,char* _str)
{
int i = 0;
int j = 0;
if (_value < 0) {
_value = -_value;
_str[i++] = '-';
}
do {
_str[i++] = _value % 10 + '0';
_value /= 10;
} while (_value);
_str[i] = '\0';
if (_str[0] == '-') {
j = 1;
++i;
}
for (; j < i / 2; j++){
_str[j] ^= _str[i - 1 - j];
_str[i - 1 - j] ^= _str[j];
_str[j] ^= _str[i - 1 - j];
}
return _str;//返回转换后的值
}
char* getHint(char* secret, char* guess) {
int bull = 0;
int cow = 0;
int temp = 0;
int size[2] = { 0 };
int buff[2][10] = { 0 };
int len = strlen(secret);
/* 求出两组字符串的数字的个数,如果位置和值都相同就记录公牛 */
for (int i = 0; i < len; i++) {
if (secret[i] == guess[i]) {
bull++;
} else {
buff[0][secret[i] - '0'] ++;
buff[1][guess[i] - '0'] ++;
}
}
for (int i = 0; i < 10; i++) {
if (0 == buff[0][i]){
continue;
}
/* 数字有值,选个数少的为奶牛 */
if (buff[0][i] < buff[1][i]){
cow += buff[0][i];
}else {
cow += buff[1][i];
}
//printf("number is %d cow = %d\r\n",i,cow);
}
/* 数字转字符串 */
len = 3;
temp = bull;
do {
temp /= 10;
size[0]++;
} while (temp);
temp = cow;
do {
temp /= 10;
size[1]++;
} while (temp);
len += size[0] + size[1];
char* ret = (char*)malloc(len * sizeof(char));
user_itoa(bull, ret);
user_itoa(cow, ret + size[0] + 1);
ret[size[0]] = 'A';
ret[size[0] + size[1] + 1] = 'B';
ret[size[0] + size[1] + 2] = '\0';
return ret;
}
299-中等-猜数字游戏
最新推荐文章于 2022-08-20 15:07:07 发布