PAT Grade A Zhenti 1027 Colors in Mars [string + hexadecimal conversion] solution

table of Contents

1. Title

Martians express colors in computers in a similar way to earthly people.

In other words, the color is represented by 6 digits. The first 2 digits represent red ®, the middle 2 digits represent green (G), and the last 2 digits represent blue (B).

The difference with us is that they use 13 bases (0∼9 and A∼C) to represent color values.

Now given three decimal numbers used to represent color values ​​(the number range is between [0,168]), please output their Martian RGB color values.

The input format
contains three decimal integers, representing the R, G, and B color values ​​in decimal.

The output format is
one line, output a "#" first, and then output a 6-digit number to represent the RGB color value of Mars.

If the value of a certain color is converted into a 13 hexadecimal system and it is less than 2 digits, add 0 to the front to make up 2 digits.

Sample Input:
15 43 71
Output Sample:
#123456
Sample explanation
given number three 15, 43, 71represents the hexadecimal 13 respectively 12, 34, 56.

So put them together and the answer is #123456.

2. Code

Understand the usage of a function: The
reverse function is used to reverse the order within the range of [first,last) (including the element pointed to by first, excluding the element pointed to by last)
such as:

string str="www.mathor.top";
reverse(str.begin(),str.end());//str结果为pot.rohtam.wwww
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string>
using namespace std;
string calc(int n)   //进制转换
{
    
    
    string str;
    while(n)
    {
    
    
        if(n%13<=9)
          str+=n%13 +'0';
        else
          str+=n%13- 10 +'A';
        n/=13;
    }
    reverse(str.begin(),str.end());     //将字符串翻转
    while(str.size()<2)  str='0'+str;   //不足二位,补零
    return str;
}
int main()
{
    
    
    int a[3];
    cin>>a[1]>>a[2]>>a[3];
    cout<<'#';
    for(int i=1;i<=3;i++)
    {
    
        
        cout<<calc(a[i]);
    }
    cout<<endl;
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45629285/article/details/109518538