Bulls and Cows

You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls") and how many digits match the secret number but locate in the wrong position (called "cows"). Your friend will use successive guesses and hints to eventually derive the secret number.

中文:假设你正在玩猜数字游戏(Bulls and Cows):你写出4个数字让你的朋友猜,每次你的朋友猜一个数字,你给出一条线索,这个线索告诉你的朋友,有多少个数字位置是正确的(被称为Bulls),有多少个数字位置是不正确的(被称为Cows),你的朋友需要根据这些线索最终猜出正确的数字。

class Solution {
public:
    string getHint(string secret, string guess) {
        if(secret.length() == 0 || guess.length() == 0)
            return "0A0B";
        
        int aNum = 0;
        int bNum = 0;
        int counts[10]; //定义数组存放0~9,这样只需遍历一遍字符串
        for(int i = 0;i<10;i++){
            counts[i] = 0;
        }
        
        for(int i=0; i< secret.length();i++){
            if(secret[i] == guess[i]){
                aNum++;
            }else{
                counts[secret[i] - '0']++;
                if(counts[secret[i] - '0']<=0){
                    bNum++;
                }
                
                counts[guess[i] - '0']--;
                if(counts[guess[i] - '0']>=0){
                    bNum++;
                }
            }
        }
        
        
        return to_string(aNum)+"A"+to_string(bNum)+"B"; //to_string()转换字符串
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值