PAT-A 1027 Colors in Mars (20 分)

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

思路:

思路1:正常进制转换。代码是这种思路。

思路2:由于转换后最多为两位,可以在一个字符数组中保存0~9和A~C,根据a / 13 和a % 13计算每位字符在数组中的位置。
#include <iostream>
#include <string>

using namespace std;

int main()
{
    int in;
    string out = "#";//保存最终要输出的字符串
    for(int i = 0; i < 3; i++)
    {
        cin >> in;
        int times = 0;//记录转换后的十三进制的位数
        int remainder;//记录进制转换时的余数
        string temp = "";//记录每次进制转换后的两位字符
        do
        {
            remainder = in % 13;
            in = in / 13;
            if(remainder < 10)
                temp += (char)('0' + remainder);
            else
                temp += (char)('A' + remainder - 10);
            times++;//记录是否应该补0
        }while(in);
        if(1 == times)
            temp += "0";
        //交换十三进制两个字符的数字
        char c = temp[0];
        temp[0] = temp[1];
        temp[1] = c;
        //拼接新的字符
        out += temp;
    }
    cout << out;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38127801/article/details/86219513