Base Conversion
EPI 7.2
Description:
number as string, convert from base b1 to base b2
Example:
Note
Idea:
- Convert to integer number
- Convert from integer number to string
Code:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cctype>
using namespace std;
string intToString(int num, int b){
bool isNegative= num<0;
num=abs(num);
string result;
while(num){
int digit = num%b;
result.push_back(digit>=10? digit-10+'A': digit+'0');
num=num/b;
}
if(isNegative)
result += '-';
return string(result.rbegin(), result.rend());
}
string baseConversion(string num, int b1, int b2){
int numInt=0;
bool isNegative= num[0] =='-';
for(int i=isNegative?1:0 ; i<num.size(); i++ ){
int digit= isdigit(num[i])? num[i]-'0': num[i]-'A'+10;
numInt = numInt*b1 + digit;
}
return intToString(numInt, b2);
}
int main(){
cout<<baseConversion("102", 3, 4);
}