Add two integers of different base and represent sum in smaller base of the two | 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 ; To reverse the string ; Driver Code ; Integer in base 10 ; Sum of integers ; Minimum Base ; Sum of integers in Min Base
#include <bits/stdc++.h> NEW_LINE using namespace std ; int val ( char c ) { if ( c >= '0' && c <= '9' ) return ( int ) c - '0' ; else return ( int ) c - ' A ' + 10 ; } int convert ( string num , int base ) { int len = ( num . size ( ) ) ; int power = 1 ; int res = 0 ; int i ; for ( i = len - 1 ; i >= 0 ; i -- ) { res += val ( num [ i ] ) * power ; power = power * base ; } return res ; } int dec_to_base ( int num , int base ) { string base_num = " " ; while ( num > 0 ) { int dig = int ( num % base ) ; if ( dig < 10 ) base_num += to_string ( dig ) ; else base_num += to_string ( ' A ' + dig - 10 ) ; num /= base ; } reverse ( base_num . begin ( ) , base_num . end ( ) ) ; return stoi ( base_num ) ; } int main ( ) { 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 = min ( base_a , base_b ) ; cout << ( dec_to_base ( summ , min_base ) ) ; }