UVA 10473 - Simple Base Conversion
題目:
在這個問題中你被要求寫一個程式來做數字基底的轉換。給你一個10進位或16進位的數,請你把他轉換成16進位或10進位的數。16進位的數總是以0x當開頭,其他所有的數都被當成是10進位。輸入中不會有不合法的數。
Input
輸入含有多組測試資料。每組測試資料一列有一個不為負數的數,可能是一個10進位或16進位的數。請根據上述的敘訴判斷。這個數10進位的值一定小於 231 。 若輸入為負的10進位數字時代表輸入結束。請參考 Sample Input。
Output
對每組測試資料輸出一列。如果輸入的是10進位的數,請輸出其16進位的值。如果輸入是16進位的數,請輸出其10進位的值。 如同輸入一樣,輸出的16進位的數也請以 0x 開頭。請參考Sample Output。
Sample Input #1
4
7
44
0x80685
-1
Sample Output #1
0x4
0x7
0x2C
525957
C++ code:
#include<bits/stdc++.h>
using namespace std;
int main(){
//ios::sync_with_stdio(0);cin.tie(0);
string n;
while(cin >> n) {
if (n == "-1") {
break;
}
else if (n.substr(0, 2) == "0x") {
string ans = n.substr(2);
istringstream iss(ans);
int answer;
if (iss >> hex >> answer) {
cout << dec << answer << endl;
}
}
else {
int a = stoi(n);
if (a > 0) {
cout << "0x" << hex << uppercase << a << endl;
}
}
}
}