巧解进制转换题
作者:互联网
问题
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 to its left.
Sample Input:
15 43 71
结尾无空行
Sample Output:
#123456
思路
此处限定了rgb三个维度的十进制数范围是【1,168】刚好是两个数位的13进制数的表示范围。于是可以使用char数组存储0-9,A-C.这样数组下标和元素刚好一一对应。1-168的数除于13,商是13进制下的第一个数位。而这个数对13求余,余数是13进制下的第二个数位。利用字符数组输出即可。
代码
#include<bits/stdc++.h>
using namespace std;
char str[13] = {'0','1','2','3','4','5','6','7','8','9','A','B','C'};
int a,b,c,base=13;
int main(){
cin>>a>>b>>c;
cout<<"#";
cout<<str[a/base]<<str[a%base]<<str[b/base]<<str[b%base]<<str[c/base]<<str[c%base];
cout<<endl;
return 0;
}
总结
进制转换可以采用模板化的方法,即除基取余法,将结果存储在数组里。当题目限定了数的大小范围的时候,可以考虑采用其他更简单的方法。
标签:13,转换,进制,color,digit,巧解,Mars,output 来源: https://blog.csdn.net/qq_19272233/article/details/119322115