PTA 1027 Colors in Mars (20 分)燚
People in Mars represent the colors in their computers in a similar way as the Earth people. That is, a color is represented by a 6-digit number, where the first 2 digits are for Red
, the middle 2 digits for Green
, and the last 2 digits for Blue
. The only difference is that they use radix 13 (0-9 and A-C) instead of 16. Now given a color in three decimal numbers (each between 0 and 168), you are supposed to output their Mars RGB values.
Input Specification:
Each input file contains one test case which occupies a line containing the three decimal color values.
Output Specification:
For each test case you should output the Mars RGB value in the following format: first output #
, then followed by a 6-digit number where all the English characters must be upper-cased. If a single color is only 1-digit long, you must print a 0
Sample Input:
15 43 71
Sample Output:
#123456
題目大意:顏色由 R G B 三個字元表示,每個字元對應一個十三進位制數。現給出 RGB 三個十進位制數,將他們轉換位十三進位制數
輸出以#字元開始
思路:1.由於最後輸出的有“#”字元,並且13進位制涉數大於9的都用字母表示,因此選擇用char 或string型別來儲存。
2.因為int型別轉char型別比較麻煩,可將單個的char型別當作string類,所以選擇string型別
3.十進位制轉十三進製為連續除13取餘並反向輸出,為了方便可以用棧臨時儲存
注意事項: If a single color is only 1-digit long, you must print a 0
to its left. 如果轉換的13進位制數只有一位,高位用0補齊
#include<iostream>
#include<stack>
#include<vector>
#include<string>
using namespace std;
//將十進位制數轉換為13進位制數
void changeNum(vector<string>&result, int n) {
stack<int> s;//儲存轉換的13進位制數
//如果十進位制數為0則將0壓入棧中
if (n == 0) {
s.push(0);
}
//連續取餘進位制轉換
while (n != 0) {
int temp = n % 13;
s.push(temp);
n /= 13;
}
//如果13進位制數只有一位,則用零補齊
if (s.size() == 1) {
s.push(0);
}
//將13進位制數轉換為字串
while (!s.empty()) {
if (s.top() > 9) {
switch (s.top()) {
case 10:result.push_back("A");break;
case 11:result.push_back("B");break;
case 12:result.push_back("C");break;
}
s.pop();
}
else {
result.push_back(to_string(s.top()));
s.pop();
}
}
}
int main() {
vector<string>result;
//3個十進位制數,邊輸入邊轉換
for (int i = 0;i < 3;i++) {
int n;
cin >> n;
changeNum(result, n);
}
//輸出
cout << "#";
for (int i = 0;i < result.size();i++) {
cout << result[i];
}
cout << endl;
return 0;
}