Multiply Large Numbers represented as Strings | C # program to multiply two numbers represented as Strings . ; Multiplies str1 and str2 , and prints result . ; will keep the result number in vector in reverse order ; Below two indexes are used to find positions in result . ; Go from right to left in num1 ; To shift position to left after every multipliccharAtion of a digit in num2 ; Go from right to left in num2 ; Take current digit of second number ; Multiply with current digit of first number and add result to previously stored result charAt current position . ; Carry for next itercharAtion ; Store result ; store carry in next cell ; To shift position to left after every multipliccharAtion of a digit in num1 . ; ignore '0' s from the right ; If all were '0' s - means either both or one of num1 or num2 were '0' ; genercharAte the result String ; Driver code
using System ; class GFG { static String multiply ( String num1 , String num2 ) { int len1 = num1 . Length ; int len2 = num2 . Length ; if ( len1 == 0 len2 == 0 ) return "0" ; int [ ] result = new int [ len1 + len2 ] ; int i_n1 = 0 ; int i_n2 = 0 ; int i ; for ( i = len1 - 1 ; i >= 0 ; i -- ) { int carry = 0 ; int n1 = num1 [ i ] - '0' ; i_n2 = 0 ; for ( int j = len2 - 1 ; j >= 0 ; j -- ) { int n2 = num2 [ j ] - '0' ; int sum = n1 * n2 + result [ i_n1 + i_n2 ] + carry ; carry = sum / 10 ; result [ i_n1 + i_n2 ] = sum % 10 ; i_n2 ++ ; } if ( carry > 0 ) result [ i_n1 + i_n2 ] += carry ; i_n1 ++ ; } i = result . Length - 1 ; while ( i >= 0 && result [ i ] == 0 ) i -- ; if ( i == - 1 ) return "0" ; String s = " " ; while ( i >= 0 ) s += ( result [ i -- ] ) ; return s ; } public static void Main ( String [ ] args ) { String str1 = "1235421415454545454545454544" ; String str2 = "1714546546546545454544548544544545" ; if ( ( str1 [ 0 ] == ' - ' str2 [ 0 ] == ' - ' ) && ( str1 [ 0 ] != ' - ' str2 [ 0 ] != ' - ' ) ) Console . Write ( " - " ) ; if ( str1 [ 0 ] == ' - ' && str2 [ 0 ] != ' - ' ) { str1 = str1 . Substring ( 1 ) ; } else if ( str1 [ 0 ] != ' - ' && str2 [ 0 ] == ' - ' ) { str2 = str2 . Substring ( 1 ) ; } else if ( str1 [ 0 ] == ' - ' && str2 [ 0 ] == ' - ' ) { str1 = str1 . Substring ( 1 ) ; str2 = str2 . Substring ( 1 ) ; } Console . WriteLine ( multiply ( str1 , str2 ) ) ; } }