Sum of an array of large numbers | Java program for the above approach ; Function to print the result of the summation of numbers having K - digit ; Reverse the array to obtain the result ; Print every digit of the answer ; Function to calculate the total sum ; Stores the array of large numbers in integer format ; Convert each element from character to integer ; Stores the carry ; Stores the result of summation ; Initialize the sum ; Calculate sum ; Update the sum by adding existing carry ; Store the number of digits ; Increase count of digits ; If the number exceeds 9 , Store the unit digit in carry ; Store the rest of the sum ; Append digit by digit into result array ; Append result until carry is 0 ; Print the result ; Driver Code ; Given N array of large numbers
import java . util . * ; import java . lang . * ; class GFG { static void printResult ( ArrayList < Integer > result ) { Collections . reverse ( result ) ; int i = 0 ; while ( i < result . size ( ) ) { System . out . print ( result . get ( i ) ) ; i ++ ; } } static void sumOfLargeNumbers ( String v [ ] , int k , int N ) { ArrayList < ArrayList < Integer > > x = new ArrayList < > ( 1000 ) ; for ( int i = 0 ; i < k ; i ++ ) x . add ( new ArrayList < Integer > ( ) ) ; for ( int i = 0 ; i < k ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { x . get ( i ) . add ( v [ i ] . charAt ( j ) - '0' ) ; } } int carry = 0 ; ArrayList < Integer > result = new ArrayList < > ( ) ; for ( int i = N - 1 ; i >= 0 ; i -- ) { int sum = 0 ; for ( int j = 0 ; j < k ; j ++ ) sum += x . get ( j ) . get ( i ) ; sum += carry ; int temp = sum ; int count = 0 ; while ( temp > 9 ) { temp = temp % 10 ; count ++ ; } long l = ( long ) Math . pow ( 10 , count ) ; if ( l != 1 ) carry = ( int ) ( sum / l ) ; sum = sum % 10 ; result . add ( sum ) ; } while ( carry != 0 ) { int a = carry % 10 ; result . add ( a ) ; carry = carry / 10 ; } printResult ( result ) ; } public static void main ( String [ ] args ) { int K = 10 ; int N = 5 ; String arr [ ] = { "1111111111" , "1111111111" , "1111111111" , "1111111111" , "1111111111" } ; sumOfLargeNumbers ( arr , N , K ) ; } }