问题描述
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.
输入格式
Each input file contains one test case which occupies a line containing the three decimal color values.
输出格式
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.
输入样例
15 43 71
输出样例
#123456
C语言代码
#include<stdio.h>
#include<stdlib.h>
const int radix = 13; //表示 13 进制
//得到数字对应的13进制数,用字符数组倒叙存储结果
void change(int n, char str[]){
int num = 0; //表示位数
if(n < radix) { //对于 1-digit long 的存储为 x0 形式
if(n < 10) str[0] = n + '0';
else if(n == 10) str[0] = 'A';
else if(n == 11) str[0] = 'B';
else str[num++] = 'C';
str[1] = '0';
return;
}
else{
do{ //循环得到每一位代表数字的字符
int a = n % radix;
if(a < 10) str[num++] = a + '0';
else if(a == 10) str[num++] = 'A';
else if(a == 11) str[num++] = 'B';
else str[num++] = 'C';
n = n / radix;
}while(n != 0);
return;
}
}
int main(){
int num1, num2, num3;
char s1[2], s2[2], s3[2];
scanf("%d%d%d", &num1, &num2, &num3);
change(num1 , s1);
change(num2 , s2);
change(num3 , s3);
printf("#%c%c%c%c%c%c", s1[1], s1[0], s2[1], s2[0], s3[1], s3[0]);
return 0;
}
代码改进
已知输入的数据转化成13进制都是两位数,因此直接用数组 radix[13] 表示出可能的结果,根据 num /13 得到第一位,num%13得到第二位即可,代码如下
#include<stdio.h>
char radix[13] = { '0' , '1' , '2' , '3' , '4' , '5' , '6' ,
'7' , '8' , '9' , 'A' , 'B' , 'C'};
int main(){
int r , g , b;
scanf("%d%d%d", &r, &g, &b);
printf("#");
printf("%c%c", radix[r / 13], radix[r % 13]);
printf("%c%c", radix[g / 13], radix[r % 13]);
printf("%c%c", radix[b / 13], radix[r % 13]);
return 0;