Bulls and Cows(Easy) 猜数字游戏

英文:You are playing the following Bulls and Cows game with your friend: You write a 4-digit secret number and ask your friend to guess it, each time your friend guesses a number, you give a hint, the hint tells your friend how many digits are in the correct positions (called "bulls") and how many digits are in the wrong positions (called "cows"), your friend will use those hints to find out the secret number.

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

例如,给出的数字是1807,你的朋友猜的是7810,这里用A代表Bulls,B代表Cows,则给出的线索是1A3B。

题目中给出的secret(被猜测数字)和guess(猜测的数字)长度一定是一样的。

Java代码

public String getHint(String secret, String guess) {
        int bulls = 0;
        int cows = 0;
        int[] numbers = new int[10];
        for (int i = 0; i<secret.length(); i++) {
            int s = Character.getNumericValue(secret.charAt(i));
            int g = Character.getNumericValue(guess.charAt(i));
            if (s == g) bulls++;
            else {
                //if prev part of guess has curr digit in secret
                //then we found a pair that has same digit with different position
                if (numbers[s] < 0) cows++;

                //if prev part of secret has curr digit in guess
                //then we found a pair that has same digit with different position           
                if (numbers[g] > 0) cows++;

                numbers[s] ++;
                numbers[g] --;
            }
        }
        return bulls + "A" + cows + "B";
}

results matching ""

    No results matching ""