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.

For example:

Secret number: "1807"
Friend's guess: "7810"
Hint: 1 bull and 3 cows. (The bull is 8, the cows are 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".
You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal.

创建两个变量A, B记录bulls和cows的个数,bulls的个数很简单,记录对应位置字符相等的个数。创建两个数组,保存对应位置不相等时的字符个数。最后累加两个数组中相同位置值小的元素就是B的值。代码如下:

public class Solution {
public String getHint(String secret, String guess) {
int[] a = new int[10];
int[] b = new int[10];
int A = 0;
int B = 0;
for(int i = 0; i < secret.length(); i++) {
if(secret.charAt(i) == guess.charAt(i)) {
A ++;
} else {
a[secret.charAt(i) - '0'] ++;
b[guess.charAt(i) - '0'] ++;
}
}
for(int i = 0; i < a.length; i++) {
B += Math.min(a[i], b[i]);
}
String s = A + "A" + B + "B";
return s;
}
}
资源下载链接为: https://pan.quark.cn/s/502b0f9d0e26 在进行STM32F103C8T6与HC - 06蓝牙模块、PC端以及ROS(机器人操作系统)的串口通信测试时,我们编写了以下程序。 硬件连接 将STM32F103C8T6的USART1的TX(PA9)引脚与HC - 06的RX引脚相连,同时将USART1的RX(PA10)引脚与HC - 06的TX引脚相连,以实现两者之间的串口通信。 另外,通过串口转USB模块(如CH340等)将STM32F103C8T6与PC端连接起来,方便在PC端进行通信数据的发送和接收。 程序功能 初始化USART1,设置波特率为9600,用于与HC - 06通信。同时,初始化USART2(连接串口转USB模块),波特率同样设置为9600,用于与PC端通信。 在主循环中,STM32F103C8T6不断检测USART1和USART2是否有数据接收。当从USART1(HC - 06)接收到数据时,将数据暂存到一个缓冲区中,然后通过USART2发送给PC端。反之,当从USART2(PC端)接收到数据时,也暂存到缓冲区,再通过USART1发送给HC - 06。这样就实现了STM32F103C8T6作为中间节点,将HC - 06与PC端的数据进行转发。 硬件连接 HC - 06蓝牙模块通过串口与STM32F103C8T6连接,如上所述。 程序功能(蓝牙通信部分) HC - 06在默认状态下会自动进入配对模式,等待与手机或其他蓝牙设备配对。当配对成功后,它会将从蓝牙设备接收到的数据通过串口发送给STM32F103C8T6。同时,它也会将STM32F103C8T6发送过来的数据转发给已配对的蓝牙设备。在本测试程序中,主要关注其与STM32F103C8T6之间的串口通信功能,确保数据能够正确地在两者之间传输。 硬件连接 通过串口
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值