# 跪求算法！该如何解决(2)

www.MyException.Cn  网友分享于：2013-01-21  浏览：5次

------解决方案--------------------

Java code
```
public String t3(){
int A = 0;
int B = 0;
int num1 = 1345;
int num2 = 1534;

if(num1 == num2){
A = 4;
B = 0;
return A+"A"+B+"B";
}

String str1 = "" + num1;
String str2 = "" + num2;

char[] chars1 = str1.toCharArray();
char[] chars2 = str2.toCharArray();
for(int i =0 ; i< chars1.length;i++){
int c = chars1[i];
if(str2.indexOf(c) != -1){//有此
if(str2.charAt(i) == c){
A ++ ;
}else{
B ++;
}
}
}

return A+"A"+B+"B";
}
------解决方案--------------------Java code  public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
for (;;) {
String num1 = in.nextLine();
String num2 = in.nextLine();
int a = 0;
for (int i = 0; i < 4; i++) {
int n1 = num1.charAt(i) - '0';
int n2 = num2.charAt(i) - '0';
if (n1 == n2) {
a++;
}
}
int b = 0;
for (int i = 0; i < 10; i++, mask1 >>= 1, mask2 >>= 1) {
int m1 = mask1 & 1;
int m2 = mask2 & 1;
if (m1 + m2 == 2) {
b++;
}
}
System.out.printf("%dA%dB%n", a, b);
}
}
------解决方案--------------------使用二进制计数器，等价于数组计数器Java code    Scanner in = new Scanner(System.in);
for (;;) {
String num1 = in.nextLine();
String num2 = in.nextLine();
int[] count1 = new int[10];
int[] count2 = new int[10];
int a = 0;
for (int i = 0; i < 4; i++) {
int n1 = num1.charAt(i) - '0';
int n2 = num2.charAt(i) - '0';
count1[n1]++;
count2[n2]++;
if (n1 == n2) {
a++;
}
}
int b = 0;
for (int i = 0; i < 10; i++) {
if (count1[i] + count2[i] == 2) {
b++;
}
}
System.out.printf("%dA%dB%n", a, b);
}```