LeetCode 299 Bulls and Cows

经典的猜数字题目
全对的简单,就是比较就好了
然后关键是B,如样例
Secret number: “1123”
Friend’s guess: “0111”
要输出1A1B
具体看代码
做这4道题第一道一遍AC
因为还要return string
顺便活用了stringstream

class Solution {
public:
    string getHint(string secret, string guess) {
        int ansa = 0, ansb = 0;
        int bs[10] = {0};
        int bg[10] = {0};
        for (int i = 0; i < secret.size(); i++) {
            if (secret[i] == guess[i]) ansa++;
            bs[secret[i] - '0']++;
            bg[guess[i] - '0']++;
        }
        for (int i = 0; i < 10; i++) {
            ansb += min(bs[i], bg[i]);
        }
        ansb -= ansa;
        stringstream ss;
        ss << ansa << 'A' << ansb << 'B';
        string s;
        ss >> s;
        return s;
    }
};

你可能感兴趣的:(LeetCode 299 Bulls and Cows)