簡體   English   中英

給定一個數組,使用加法和減法找到等於目標值的所有組合(2 個整數)

[英]Given an array, find all combinations (2 integers) using addition and subtraction that equal a target value

我正在嘗試制作一個程序來解決等於目標值的所有 2 個加減法組合。

例如,給定數組 [12,1,9,11,32,19] 和目標值 20,則必須返回答案 1+19、9+11 和 32-12。 如果沒有可能的組合,系統應該打印沒有可能的組合。 此外,每個組合只能是兩個數字。 是否可以僅在主 class 中執行此操作?

import java.util.Arrays;
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("What length (in a whole number) would you like the array to be? ");
        int arraySize = sc.nextInt();

        int [] arr = new int[arraySize];
        for (int i = 0; i < arraySize; i++) {
            int remainingNumbers = arraySize - i;
            System.out.println("Please enter " + remainingNumbers + " more integers.");
            arr[i] = sc.nextInt();
        }

        System.out.print("Please enter a target value: ");
        int target = sc.nextInt();
        System.out.println(Arrays.toString(arr));

   // Algorithm here.

    }
}

 import java.util.Scanner; public class Exercise6 { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Input first number: "); int num1 = in.nextInt(); System.out.print("Input second number: "); int num2 = in.nextInt(); System.out.println(num1 + " + " + num2 + " = " + (num1 + num2)); System.out.println(num1 + " - " + num2 + " = " + (num1 - num2)); System.out.println(num1 + " x " + num2 + " = " + (num1 * num2)); System.out.println(num1 + " / " + num2 + " = " + (num1 / num2)); System.out.println(num1 + " mod " + num2 + " = " + (num1 % num2)); } }

enter code here

''' Input first number: 32 Input second number: 12 19 + 1 = 20 32 - 12 = 20 9+11= 20'

是的,只能在主 class 中執行此操作。 甚至可以只在 main 方法中進行(盡管使用自己的方法更好,更容易理解)。 只有兩個嵌套for循環; 一個用於第一個值,一個用於第二個值。 在內部循環中,只需測試兩個值的總和是否產生預期的結果,減法相同。 設置一個 boolean 表示至少找到一個案例。 如果未設置 boolean,則最后打印否定消息。

樣本:

private static boolean findCombinations(int target, int[] values) {  // or ,int... values) {
    boolean found = false;
    for (int i = 0; i < values.length; i++) {
        // second loop
            // tests and print
    }
    return found;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM