Add two integers of different base and represent sum in smaller base of the two | Java Program to find the sum of two integers of different bases . ; Initialize power of base ; Initialize result ; Decimal equivalent is str [ len - 1 ] * 1 + str [ len - 2 ] * base + str [ len - 3 ] * ( base ^ 2 ) + ... ; Maximum base - 36 String base_num = " " ; ; print ans in reverse order ; Driver Code ; Integer in base 10 ; Sum of integers ; Minimum Base ; Sum of integers in Min Base
import java . util . * ; class GFG { static int val ( char c ) { if ( c >= '0' && c <= '9' ) return ( int ) c - '0' ; else return ( int ) c - ' A ' + 10 ; } static int convert ( String num , int bases ) { int len = ( num . length ( ) ) ; int power = 1 ; int res = 0 ; int i ; for ( i = len - 1 ; i >= 0 ; i -- ) { res += val ( num . charAt ( i ) ) * power ; power = power * bases ; } return res ; } static void dec_to_base ( int num , int bases ) { StringBuilder base_num = new StringBuilder ( ) ; while ( num > 0 ) { int dig = ( num % bases ) ; if ( dig < 10 ) base_num . append ( String . valueOf ( dig ) ) ; else base_num . append ( String . valueOf ( ( ' A ' + dig - 10 ) ) ) ; num /= bases ; } for ( int i = base_num . length ( ) - 1 ; i >= 0 ; i -- ) System . out . print ( base_num . charAt ( i ) ) ; } public static void main ( String [ ] args ) { String a = "123" ; String b = "234" ; int base_a = 6 ; int base_b = 8 ; int a10 = convert ( a , base_a ) ; int b10 = convert ( b , base_b ) ; int summ = a10 + b10 ; int min_base = Math . min ( base_a , base_b ) ; dec_to_base ( summ , min_base ) ; } }