給定等式其中每個字母代表一個數字,且不同數字對應不同字母。編程求出這些數字並且打出這個數字的算術計算豎式。
A B C D E
+ D F G
+ D F G
——————————
X Y Z D E
ABCDEFGXYZ十個字母各不相等並且分別代表0~9
試過用for循環遍歷,但是判斷條件想得頭都大了。同時經常漏掉判斷條件得出很多個錯誤答案
試過用數組代表0~9先求出算數式再代入字母,依然不知從何下手
也試過先找出隱性條件例G==0 F==5 X==A+1 B>=8 但是想得還是頭大。
求:
解這個題目是否需要用到算法?
盡量簡短的實現代碼
萬分感謝~~~
package test;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class Test {
/**
* @param args
*/
private static Map<String, Integer> map = new HashMap<String, Integer>();
private static Map<String, String> maps = new HashMap<String, String>();
static {
for (int i = 0; i < 10; i++) {
byte[] bytes = { (byte) (97 + i) };
map.put(new String(bytes).toUpperCase(), i);
maps.put(i+"", new String(bytes).toUpperCase());
}
maps.put(" ", " ");
maps.put("+", "+");
}
public static Long[] strToLong(String[] ag) {
Long[] lo = new Long[ag.length + 1];
Long res = 0L;
for (int i = 0; i < ag.length; i++) {
char[] ch = ag[i].toCharArray();
String str = "";
for (int j = 0; j < ch.length; j++) {
str = str + map.get(String.valueOf(ch[j])) + "";
}
lo[i] = Long.valueOf(str);
res += lo[i];
}
lo[lo.length - 1] = res;
Arrays.sort(lo);
return lo;
}
public static String[] maxLong(Long[] str) {
String[] rest = new String[str.length];
long maxLen = str[str.length - 1].toString().length();
for (int i = 0; i < str.length; i++) {
long Len = str[i].toString().length();
long sub = maxLen - Len;
String s = "";
for (int j = 0; j < sub; j++) {
s = " " + s;
}
s = s + str[i];
rest[i] = s;
}
return rest;
}
public static void main(String[] args) {
String[] ag = { "BAAAA", "BAAA", "BAABB", "BAABB" };
Long[] lo = strToLong(ag);
String[] str = maxLong(lo);
for (int i = 0; i < str.length; i++) {
if (i == 0 || i == str.length - 1 ){
System.out.print(" ");
} else {
System.out.print("+ ");
}
char[] byt = str[i].toCharArray();
for (int j = 0 ; j < byt.length; j++){
System.out.print(maps.get(byt[j]+""));
}
System.out.println();
if (str.length - 2 == i){
System.out.println("-------------");
}
//System.out.println(str[i]);
}
}
}