PAT甲级刷题记录——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 0to its left.

Sample Input:

15 43 71

Sample Output:

#123456

思路

这题很简单哈,也是一个很基本的进制转换的问题。庆幸的是,这题能用字符串了(因为题目说了10 11 12这三个数对应A B C)~

然后就很简单啦,如果读入的数是0,那么特判为0,否则的话就“除基取余”,一直到商是0为止,然后再把整个字符串反过来(因为余数先存储的是低位的,但是显示的话应该是高位在前),再判断当前字符串的位数,如果不足两位,就在头部插“0”,然后把读入的三个十进制数都转换一下输出就好啦~

代码

#include
#include
#include
#include
#include
#include
using namespace std;
string TentoD(int x, int D){
    string result;
    if(x==0){
        result = "0";
    }
    else{
        while(x!=0){
            int v = x%D;
            x /= D;
            if(v>=0&&v<=9) result += v+'0';
            else if(v==10) result += 'A';
            else if(v==11) result += 'B';
            else if(v==12) result += 'C';
        }
    }
    reverse(result.begin(), result.end());
    while(result.length()<2){
        result.insert(0, "0");
    }
    return result;
}
int main()
{
    int R, G, B;
    cin>>R>>G>>B;
    string RR = TentoD(R, 13);
    string GG = TentoD(G, 13);
    string BB = TentoD(B, 13);
    cout<<"#"<<RR<<GG<<BB;
    return 0;
}

你可能感兴趣的:(PAT甲级)