求算法。给定2个4位的各个位数上的数字都不重复的数字,如果他们位置和数字都相等,为A,如果数字相等位置不等,为B。例如:
给定的第1个数:5673
第2个数: 0153
这样匹配的结果为:1A1B
变换第2个数各个数字的位置:5013
这样匹配的结果为2A0B
不知道大家明白我的意思没有,跪求该算法!!!
------解决方案--------------------
楼主可以求出每个数的个十百千,然后用一个数的个十百千循环去和另一个数的个十百千比较,然后计算相同或者不同的个数,不知道楼主明白了吗?楼主可以自己整理算法
------解决方案--------------------
- Java code
import java.io.IOException;import java.util.Scanner;public class Main { public static void main(String[] args) throws IOException { String num1, num2; // user String to save **** int Scanner in = new Scanner(System.in); num1 = in.nextLine(); num2 = in.nextLine(); int A = 0, B = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (num1.charAt(i) == num2.charAt(j)) B++; } } for (int i = 0; i < 4; i++) { if (num1.charAt(i) == num2.charAt(i)) A++; } System.out.println(A + "A" + (B - A) + "B"); }}
------解决方案--------------------
- Java code
public static void main(String[] args) { int a = 5673; int b = 5013; HashMap list = new HashMap(); while (a > 0) { list.put(list.size(), a % 10); a /= 10; } int k1 = 0, k2 = 0; int i = 0; while (b > 0) { int t = b % 10; if (list.containsValue(t)) { if (list.get(i) == Integer.valueOf(t)) k1++; else k2++; } i++; b /= 10; } System.out.println(k1 + "A" + k2 + "B"); }
------解决方案--------------------
- Java code
int A = 0; int B = 0; String s1 = "5673"; String s2 = "0153"; if(s1.length() == s2.length()) { for(int i = 0; i < s1.length(); i++) { char c1 = s1.charAt(i); for(int j = 0; j < s2.length(); j++) { char c2 = s2.charAt(j); if(c1 == c2) { if(i == j) { A++; } else { B++; } } } } } System.err.println(A + "A" + B + "B");
------解决方案--------------------
- Java code
public static void main(String[] args){ int a = 0, b = 0; String s1 = "5673"; String s2 = "5013"; for (int j = 0, i = 0; i<s1.length();) { if (s1.charAt(i)==s2.charAt(j)){ if (i==j){ a++; } else{ b++; } } j++; if (j==s1.length()){ i++; j = 0; } } System.out.println(a+"A"+b+"B"); }
------解决方案--------------------
- Java code
char [] num1 = new Integer(5673).toString().toCharArray(); char [] num2 = new Integer(5013).toString().toCharArray(); int counterA = 0, counterB = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (j!=i&&num1[i] == num2[j]) counterB++; } if (num1[i] == num2[i] )counterA++; } System.out.println(counterA + "A" + counterB + "B");