u011909635 于 2013.09.16 22:59 提问

Java高要求逻辑训练题

``````   A B C D E
+    D F G
+    D F G
——————————
X Y Z D E
``````

ABCDEFGXYZ十个字母各不相等并且分别代表0~9

1个回答

wangqingchengsg   2013.11.08 09:53

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]);
}
}
``````

}