0%

PAT A1027 Colors in Mars

题目链接

我的解题思路:

写一个函数,用来将r,g,b分别转化为一个长度为2的字符串,注意字符串翻转等。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string changeTo(int n){
string s="";
int x,m=n;
if(n==0) s+="00";
while(n!=0){
x=n%13;
if(x<10) s+=(x+'0');
else s+=(x-10+'A');
n/=13;
}
if(m<13&&m>0) s+='0';//注意m可以记录n的值,最后补0
reverse(s.begin(),s.end());
return s;
}
int main(){
int a,b,c;
cin>>a>>b>>c;
string ans="#"+changeTo(a)+changeTo(b)+changeTo(c);
cout<<ans;
return 0;
}

算法笔记解法

此方法更为简洁,更好理解,直接定义一个数组存放13个字符,因为每个值都对应两个字符,也就是除以13是第一个字符,对13取余就是第二个字符的下标。

1
2
3
4
5
6
7
8
9
10
11
12
#include <cstdio>
char chs[]={'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",chs[r/13],chs[r%13]);
printf("%c%c",chs[g/13],chs[g%13]);
printf("%c%c",chs[b/13],chs[b%13]);
return 0;
}

本文标题:PAT A1027 Colors in Mars

文章作者:GavinYGM

发布时间:2020年08月23日 - 15:08

最后更新:2020年08月23日 - 15:08

原始链接:http://www.gavinygm.cn/2020/08/23/PAT-A1027-Colors-in-Mars/

许可协议: 转载请保留原文链接及作者。