You is playing the following Bulls and cows game with your friend:you write down a number and ask your friend to guess W Hat the number is. Each time your friend makes a guess, you provide a hint the indicates how many digits in said guess match your secret num ber exactly in both digit and position (called "bulls") and how many digits match the secret number but locate in the Wron G position (called "cows"). Your Friend would use successive guesses and hints to eventually derive the secret number.
For example:
Secret Number: " 1807" Friend's guess: "7810"
Hint:
1
Bull and
3
cows. (The Bull is
8
, the cows is
0
,
1
and
7
.)
write a function to return a hint according to the secret number and friend ' s guess, Use a
to indicate the Bulls and b
to indicate the cows. In the above example, your function should Return " 1a3b "
.
Please note that both secret number and friend's guess may contain duplicate digits, for example:
Secret number: " 1123" Friend's guess: "0111"
in this case, the 1st
1
in friend's guess is a bull, the 2nd or 3rd
1
is a cow, and your function should return
"1A1B"
.
Assume that the secret number and your friend's guess only contain digits, and their lengths is always equal.
Credits:
Special thanks to @jeantimex for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
You and your friends are playing the following guessing number game (bullsandcows): You write down a 4-digit mysterious number and then let your friend guess,//Your friend guesses a number at a time, you give a hint, tell him how many numbers are in the right place (called "bulls" bulls),// And how many numbers are in the wrong place (called "cows" cows), your friends use these tips to find out that mysterious number. Class Solution {Public:string Gethint (string secret, String guess) {int acnt=0;//bull number int bcnt=0;//cow's Number vector<int> Svec (10,0); Vector<int> Gvec (10,0); if (Secret.length ()!=guess.length () | | secret.empty ()) return "0a0b"; for (int i=0;i<secret.length (); ++i) {char C1=secret[i];char c2=guess[i]; if (C1==C2) ++acnt; Calculate the number of bulls else {++svec[c1-' 0 ']; ++gvec[c2-' 0 ']; }}//Calculate the number of cows for (int i=0;i<svec.size (); ++i) {bcnt+=min (Svec[i],gvec[i] ); } return To_string (acnt) + ' A ' + to_string (bcnt) + ' B '; }};
Leetcode 299:bulls and cows