I found two ways of conversion from any base to base 10 . the first one is the normal one we do in colleges like 521(base-15) ---> (5*15^2)+(2*15^1)+(1*15^0)=1125+30+1 = 1156 (base-10) . my problem is that i applied both methods to a number (1023456789ABCDE(Base-15)) but i am getting different result . google code jam accepts the value generated from second method only for this particular number (i.e 1023456789ABCDE(Base-15)) . for all other cases both generates same results . whats big deal with this special number ?? can anybody suggest ...
#include <iostream>
#include <math.h>
using namespace std;
int main()
{ //number in base 15 is 1023456789ABCDE
int value[15]={1,0,2,3,4,5,6,7,8,9,10,11,12,13,14};
int base =15;
unsigned long long sum=0;
for (int i=0;i<15;i++)
{
sum+=(pow(base,i)*value[14-i]);
}
cout << sum << endl;
//this prints 29480883458974408
sum=0;
for (int i=0;i<15;i++)
{
sum=(sum*base)+value[i];
}
cout << sum << endl;
//this prints 29480883458974409
return 0;
}
Consider using std::stol
(ref) to convert a string into a long.
It let you choose the base to use, here an example for your number wiuth base 15
.
int main()
{
std::string s = "1023456789ABCDE";
long n = std::stol(s,0,15);
std::cout<< s<<" in base 15: "<<n<<std::endl;
// -> 1023456789ABCDE in base 15: 29480883458974409
}