2 u011909635 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
试过用for循环遍历,但是判断条件想得头都大了。同时经常漏掉判断条件得出很多个错误答案
试过用数组代表0~9先求出算数式再代入字母,依然不知从何下手
也试过先找出隐性条件例G==0 F==5 X==A+1 B>=8 但是想得还是头大。
求:
解这个题目是否需要用到算法?
尽量简短的实现代码

万分感谢~~~

1个回答

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

}

Csdn user default icon
上传中...
上传图片
插入图片