首页 > 解决方案 > 将两个数组相加,求出 10 的可能组合数

问题描述

如果你有 2 个数组 1 tom和 1 ton其中mn都是>= 1and <= 1000,找出有多少种方法可以用这两个数组列表得到 10 的总和

前任:

Output: "What is m"
User Input: 7
Output: "What is n"
User Input: 5
Output: "There are 3 ways to get 10"

标签: javaarraysuser-input

解决方案


我可能会因为提供答案而被否决,因为您没有提供明确的问题,而且在社区帮助您之前,您没有表现出任何努力自己解决问题。

我能够从您的示例结果中破译的是,ArrayList如果您有两个输入mn.

从您的输入中,取最大的数字并运行从 1 到该数字的循环。从总和中减去该数字,并检查该差是否大于 0 且小于另一个数字。如果这是真的,你有办法计算 10 的总和。

就像是:

public class StackOverflow {
    public static void main(String args[]) {
        int m = 7;
        int n = 5;
        int sum = 10;

        // Take the larger of the two inputs
        int limit = m > n ? m : n;

        int count = 0;
        for (int i = 1; i <= limit; i++) {
            int possibleN = sum - i;

            // Check that the possibleN is greater than 0 and less than n
            if (0 < possibleN && possibleN <= n) {
                System.out.printf("%d + %d = %d\r\n", i, possibleN, sum);
                count++;
            }
        }

        System.out.printf("There are %d ways to get %d\r\n", count, sum);
    }
}

结果:

5 + 5 = 10
6 + 4 = 10
7 + 3 = 10
There are 3 ways to get 10

推荐阅读