[URI Online Judge] – 1193 – Base Conversion

The Julian math teacher has marked a test whose content will on to convert between decimal, hexadecimal and binary numbers. For Julian, this kind of convertion is one of the most complex things to be done. Regardless of the time spent for studying these contents, he simple don\’t understand. So, as you understand about computing and is a friend of Julian, he asked for your help to make a program that checks if the conversions made ​​by him are correct.

Input

The input contains many test cases. The first line of input contains an integer N indicating the number of test cases that follow, one by line. Each test case contains a number X (X > 0) followed by a Y text with three characters, indicating if the X number is in binary, decimal or hexadecimal. Regardless of the format, any of the numbers must fit into a 32-bit integer.

Output

For each test case, Julian wants that you print the number of the test case folloed by two lines, that contains the oiginal number converted for each one of the other two bases. The sequence of the bases of output is always: decimal, hexadecimal (lowercase) and binary, ie must respect this order obviously excluding the input format.
Note: should print a blank line after each test case, even after the last test case.

Sample Input Sample Output
3
101 bin
101 dec
8f hex
Case 1:
5 dec
5 hex

Case 2:
65 hex
1100101 bin

Case 3:
143 dec
10001111 bin

My solution:


#include <iostream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <string>

using namespace std;

char digit_hex (int x) {
if (x >= 0 && x < 10)
return x+'0';
else if (x < 16)
return x-10+'a';
else
return '!';
}

string tobin (int x) {
string aux;
while (x > 0) {
char c = x%2+'0';
aux = c + aux;
x /= 2;
}
return aux;
}

string tohex (int x) {
string aux;
while (x > 0) {
aux = digit_hex(x%16) + aux;
x /= 16;
}
return aux;
}

int main () {
char str[50];
string type;
int x, n;

cin >> n;
for (int i = 0; i < n; i++) {
cin >> str >> type;

cout << "Case " << i+1 << ':' << endl;
if (type == "bin") {
x = strtol(str, 0, 2);
cout << x << " dec" << endl;
cout << tohex(x) << " hex" << endl;
} else if (type == "dec") {
x = strtol(str, 0, 10);
cout << tohex(x) << " hex" << endl;
cout << tobin(x) << " bin" << endl;
} else {
x = strtol(str, 0, 16);
cout << x << " dec" << endl;
cout << tobin(x) << " bin" << endl;
}

cout << endl;
}

return 0;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s