MENU

第六届蓝桥杯Java B——三羊献瑞

March 13, 2019 • Read: 3385 • 算法阅读设置

观察下面的加法算式:

其中,相同的汉字代表相同的数字,不同的汉字代表不同的数字。

请你填写“三羊献瑞”所代表的4位数字(答案唯一)

public class Main {
    static int[] book = new int[10];
    static int[] res = new int[8];

    public static void main(String[] args) {
        dfs(0);
    }

    /*
     * 祥瑞生辉三羊献气 res[0]~res[7]
     */
    static void dfs(int idx) {
        if (idx == 8) {
            if (check()) {
                for (int i : res)
                    System.out.print(i + " ");
                System.out.println();
            }
            return;
        }
        for (int i = 0; i <= 9; i++) {
            if (book[i] == 0) {
                book[i] = 1;
                res[idx] = i;
                dfs(idx + 1);
                book[i] = 0;
            }
        }
    }

    static boolean check() {
        int a = res[0] * 1000 + res[1] * 100 + res[2] * 10 + res[3];
        int b = res[4] * 1000 + res[5] * 100 + res[6] * 10 + res[1];
        int c = res[4] * 10000 + res[5] * 1000 + res[2] * 100 + res[1] * 10 + res[7];
        return a + b == c && res[0] != 0 && res[4] != 0;
    }
}
Archives Tip
QR Code for this page
Tipping QR Code
Leave a Comment

已有 1 条评论
  1. Kira Kira

    哥们代码简洁易懂太牛了