TechoSagar: Convert from any base to decimal

Search

Google Alert - jobs

Convert from any base to decimal

Given a number and its base, convert it to decimal. The base of number can be anything such that all digits can be represented using 0 to 9 and A to Z. Value of A is 10, value of B is 11 and so on.
Input:
The first line of input contains an integer T denoting the number of test cases. The first line of each test case is the base and second line of test case is the number which is to be converted to decimal.

Output:
Decimal conversion of the given number is displayed in the output.

Constraints:
1 <= T <= 5
2 <= base <=16
1 <= N <= decimal equivalents till 999999999

Example:
Input:
3

1100
16
11A
8
123
Output:
12
282
83
Your Code
#include<iostream>

using namespace std;
#include<math.h>
#include<string.h>
#include<sstream>

int main()
{
int t;
cin>>t;
while(t--)
{
int b;
cin>>b;
string s;
cin>>s;
int l=s.length();
int i,number=0;
int j=0;
for(i=l-1; i>=0; i--)    
{     
   int x=10;
if(s[i]>='A' && s[i]<='Z')
{  
 char k;
for(k='A'; k<'Z'; k++)
{   if(k<s[i])
  x++;
//cout<<x<<endl;
}
}
else
{
string temp;
   temp=s[i];
stringstream ss(temp);
ss>>x;
//cout<<x<<" ";
number=number+x*pow(b,j);
j++;
        } 
        cout<<number<<endl;
}
}

Follow us

Follow Bijendra Kumar on Facebook