PAT A1027 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
to its left.
Sample Input:
15 43 71
Sample Output:
#123456
题意
R
,G
,B
三个十进制数转化为十三进制输出
思路1
- 单纯的进制转换,需要注意补齐两位
0
,最后反转结果
代码1
#include <bits/stdc++.h>
using namespace std;
const int radix = 13;
void change(int x)
{
vector<int> ans;
while(x)
{
int t = x % radix;
char c;
if(t > 9)
c = t - 10 + 'A';
else
c = t + '0';
ans.push_back(c);
x /= radix;
}
while(ans.size() != 2) ans.push_back('0');
reverse(ans.begin(), ans.end());
printf("%c%c", ans[0], ans[1]);
}
int main()
{
int R, G, B;
scanf("%d%d%d", &R, &G, &B);
printf("#");
change(R);
change(G);
change(B);
return 0;
}
思路2
0-168
转化的结果只有两位,即低位为a[i] % 13
和 高位a[i] / 13
,将这两位转化为十三进制字符即可。
代码2
#include <iostream>
using namespace std;
const int N = 3;
char get(int x)
{
if(x <= 9)
return x + '0';
else
return x - 10 + 'A';
}
int main()
{
int a[N];
for(int i = 0; i < N; i++)
scanf("%d", &a[i]);
printf("#");
for(int i = 0; i < N; i++)
printf("%c%c", get(a[i] / 13), get(a[i] % 13));
puts("");
return 0;
}