Advertisement
CoineTre

JF-ExcArrays06.EqualSums

Jan 21st, 2021
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.29 KB | None | 0 0
  1. /*
  2. Write a program that determines if there exists an element in the array such that the sum of the elements
  3. on its left is equal to the sum of the elements on its right. If there are no elements to the left / right,
  4. their sum is considered to be 0. Print the index that satisfies the required condition or “no” if there is no such index.
  5. */
  6.  
  7. import java.util.Arrays;
  8. import java.util.Scanner;
  9.  
  10. public class TestXXX {
  11.     public static void main(String[] args) {
  12.         Scanner scanner = new Scanner(System.in);
  13.         int[] numbers = Arrays.stream(scanner.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
  14.         boolean equalSums = false;
  15.         int indexN = 0;
  16.         for (int i = 0; i < numbers.length; i++) {
  17.             int leftSum = 0;
  18.             for (int j = 0; j < i ; j++) {
  19.                 leftSum += numbers[j];
  20.             }
  21.             int rightSum = 0;
  22.             for (int j = i+1; j < numbers.length; j++) {
  23.                 rightSum += numbers[j];
  24.             }
  25.             if (leftSum == rightSum){
  26.                 equalSums = true;
  27.                 indexN = i;
  28.                 break;
  29.             }
  30.         }
  31.         if (equalSums){
  32.             System.out.println(indexN);
  33.         }else{
  34.             System.out.println("no");
  35.         }
  36.     }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement