Simple Base Conversion
Time Limit:1000MS Memory Limit:65536K
Total Submit:35 Accepted:10
Description
In this problem you are asked to write a simple base conversion program. You will be given a hexadecimal or decimal integer number as input. You will have to output the corresponding decimal or hexadecimal number. Hexadecimal numbers always starts with a `0x' and all other numbers are to be considered as decimal numbers. There will be no invalid numbers in the input.
![](http://202.120.113.171/JudgeOnline/images/1002/p10473.gif)
![](http://202.120.113.171/JudgeOnline/images/1002/p10473.gif)
Input
The input file contains several lines of input. Each line contains a single non-negative number, which may be a decimal or hexadecimal number as explained in the problem statement. The decimal value of this number will be less than 231. A line containing a negative decimal number terminates input. This number should not be processed. Input numbers will contain no space within them.
Output
For each line of input (Except the last one) produce one line of output. This line should contain the decimal or hexadecimal representation of the corresponding hexadecimal or decimal number. Like the input, the hexadecimal numbers in the output should be preceded by a `0x'.
Sample Input
4 7 44 0x80685 -1
4 7 44 0x80685 -1
Sample Output
0x4 0x7 0x2C 525957
0x4 0x7 0x2C 525957
Source
UVA
-------------------code--------------------------
#include <iostream>
#include <string>
#include <sstream>
#include <cmath>
using namespace std;
int fromString(const std::string& s) {
istringstream is(s);
int t;
is >> t;
return t;
}
template<typename T>
string toString(const T& t) {
ostringstream s;
s << t;
return s.str();
}
int hexToDec(string b){
int sum=0;
int t;
for(int k=b.length()-1;k>=0;k--){
t=b[k]-'0';
if(t<10){
sum += t*pow(double(16),double(b.length()-k-1));
}
else
if(t<30){
sum += (t-7)*pow(double(16),double(b.length()-k-1));
}
else{
sum += (t-39)*pow(double(16),double(b.length()-k-1));
}
}
return sum;
}
int main(){
int a;
string g;
while(1){
cin>>g;
if (g[0]=='-') break;
if (g[0]=='0'){
g = g.substr(2,g.length()-2);
cout<<hexToDec(g)<<endl;
}
else{
a = fromString(g);
cout<<"0x";
std::cout.setf(std::ios::uppercase);
cout<<std::hex<<a<<endl;
cout<<std::dec;
}
}
return 1;
}