299. Bulls and Cows
来源:互联网 发布:淘宝教程店招加收藏 编辑:程序博客网 时间:2024/04/29 22:55
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.
我的程序:
class Solution {public:string intToStr(int a){ string s;//string to be returned if(a<0)return s; if(a==0){ s='0'; return s; } while(a>0){ int digit=a%10; char temp='0'+digit; s.insert(s.begin(),temp); a/=10; } return s;} string getHint(string secret, string guess) { int set[10]={0}; int n=secret.size(),index; int aCount=0,bCount=0; for(int i=0;i<n;i++){ index=secret[i]-'0'; if(secret[i]==guess[i]){ aCount++; swap(secret[i],secret[n-1]); swap(guess[i],guess[n-1]); n--; i--; } else set[index]++; } for(int i=0;i<n;i++){ index=guess[i]-'0'; if(set[index]>0){ bCount++; set[index]--; } } string s,a=intToStr(aCount),b=intToStr(bCount); s=a+"A"+b+"B"; //string to be returned return s; }};
- 299. Bulls and Cows
- 299. Bulls and Cows
- 299. Bulls and Cows
- 299. Bulls and Cows
- 299. Bulls and Cows
- 299. Bulls and Cows
- 299. Bulls and Cows
- 299. Bulls and Cows
- 299. Bulls and Cows
- 299. Bulls and Cows
- 299. Bulls and Cows
- 299. Bulls and Cows
- 299. Bulls and Cows
- 299. Bulls and Cows
- 299. Bulls and Cows
- 299. Bulls and Cows
- 299. Bulls and Cows
- 299. Bulls and Cows
- inode dentry 硬链接 符号链接 关系
- java过滤器-双向过滤
- 2013上半年—嵌入式系统开发—中考
- Quartz任务调度器及与Spring的整合使用
- 2013上半年—Linux操作系统—中考
- 299. Bulls and Cows
- arm linux 内核生成过程
- js中,删除数组中指定的某个元素
- VisionMobile:2015年Android使用的全球趋势(六)巴西喜欢WI-FI,印度喜欢蜂窝
- android 数据库更新
- 向日葵远程控制软件发布Linux被控端1.0Beta版
- Unity ZTest 深度测试 & ZWrite 深度写入
- 我所知道的云计算
- redis配置文件redis.conf详细说明