Program to add two integers of given base | Java implementation to find the sum of two integers of base B ; Function to find the sum of two integers of base B ; Padding 0 in front of the number to make both numbers equal ; Condition to check if the strings have lengths mis - match ; Loop to find the find the sum of two integers of base B ; Current Place value for the resultant sum ; Update carry ; Find current digit ; Update sum result ; Driver Code ; Function Call
class GFG { static String sumBaseB ( String a , String b , int base ) { int len_a , len_b ; len_a = a . length ( ) ; len_b = b . length ( ) ; String sum , s ; s = " " ; sum = " " ; int diff ; diff = Math . abs ( len_a - len_b ) ; for ( int i = 1 ; i <= diff ; i ++ ) s += "0" ; if ( len_a < len_b ) a = s + a ; else b = s + b ; int curr , carry = 0 ; for ( int i = Math . max ( len_a , len_b ) - 1 ; i > - 1 ; i -- ) { curr = carry + ( a . charAt ( i ) - '0' ) + ( b . charAt ( i ) - '0' ) ; carry = curr / base ; curr = curr % base ; sum = ( char ) ( curr + '0' ) + sum ; } if ( carry > 0 ) sum = ( char ) ( carry + '0' ) + sum ; return sum ; } public static void main ( String [ ] args ) { String a , b , sum ; int base ; a = "123" ; b = "234" ; base = 6 ; sum = sumBaseB ( a , b , base ) ; System . out . println ( sum ) ; } }