Sum Of Two Array [codingblocks]
Take as input N, the size of array. Take N more inputs and store that in an array. Take as input M, the size of second array and take M more inputs and store that in second array. Write a function that returns the sum of two arrays. Print the value returned.
Input Format
Constraints
Length of Array should be between 1 and 1000.
Output Format
Sample Input
4
1 0 2 9
5
3 4 5 6 7
Sample Output
3, 5, 5, 9, 6, END
Explanation
Sum of [1, 0, 2, 9] and [3, 4, 5, 6, 7] is [3, 5, 5, 9, 6] and the first digit represents carry over , if any (0 here ).
Java Code:
IDE Code: https://ide.geeksforgeeks.org/LBbNYfYGob
/* Amit Kumar 04-12-2020 IDE Code: https://ide.geeksforgeeks.org/LBbNYfYGob */ package array; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class Array_SumOfTwoArrays { public static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { int arrSize1 = scanner.nextInt(); int[] arr1 = new int[arrSize1]; for (int i=0; i<arrSize1; i++) { arr1[i] = scanner.nextInt(); } int arrSize2 = scanner.nextInt(); int[] arr2 = new int[arrSize2]; for (int i=0; i<arrSize2; i++) { arr2[i] = scanner.nextInt(); } ArrayList<Integer> arrayList = new ArrayList<Integer>(); int carry = 0; while (arrSize1 > 0 && arrSize2 > 0) { int currSum = arr1[arrSize1-1] + arr2[arrSize2-1] + carry; carry = currSum/10; currSum = currSum%10; arrayList.add(currSum); arrSize1--; arrSize2--; } while (arrSize1 > 0) { int currSum = arr1[arrSize1-1] + carry; carry = currSum/10; currSum = currSum%10; arrayList.add(currSum); arrSize1--; } while (arrSize2 > 0) { int currSum = arr2[arrSize2-1] + carry; carry = currSum/10; currSum = currSum%10; arrayList.add(currSum); arrSize2--; } if (carry != 0) { arrayList.add(carry); } Collections.reverse(arrayList); for (Integer value : arrayList) { System.out.print(value + ", "); } System.out.print("END"); } }
Comments
Post a Comment