描述
在CSS中我们可以用井号(#)加6位十六进制数表示一种颜色,例如#000000是黑色,#ff0000是红色,#ffd700是金色。
同时也可以将六位颜色#RRGGBB简写为#RGB三位颜色。例如#000与#000000是相同的,#f00与#ff0000是相同的,#639与#663399是相同的。
对于两个颜色#abcdef和#ghijkl,我们定义其距离是(ab - gh)2 + (cd - ij)2 + (ef - kl)2。(其中ab, cd, ef, gh, ij, kl都是十六进制数,也即0~255的整数)
给定一个六位颜色#abcdef,请你求出距离它最近的三位颜色#rgb。
输入
#abcdef
其中abcdef是’0’-‘9’或’a’-‘f’。
输出
距离输入颜色最近的#rgb
样例输入
#40e0d0
#3b4b5b
#1b2b3b
样例输出
#4dc
#345
#233
思路
我的思路是把这个先分开
例如#40e0d0 分成 40,e0,d0
将他们分别转换为10进制
40=>64
e0=>244
d0=>208
因为两个字符相同的只有16个,所以我直接打表
string res[] = {"00","11","22","33","44","55","66","77","88","99","aa","bb","cc","dd","ee","ff"};
用40,e0,d0和表中的每一个分别做差即可求出想要的最小值(转换为10进制后再减)
这样就可以找出对应的位置了
40对应res[4]
e0对应res[13]
d0对应res[12]
因为结果是单字符的形式,所以输出
string res1[] = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};
res1[4],res1[13],res1[12]就可以了
完整代码
#include
#include
#include
#include
using namespace std;
string res[] = {"00","11","22","33","44","55","66","77","88","99","aa","bb","cc","dd","ee","ff"};//可能的答案
string res1[] = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};//要输出的答案
int ex(string str)//将16进制转化为10进制
{
int a = 0;
//处理第一个数字
if(str[0] >= '0' && str[0] <= '9')
{
a+=(str[0]-'0')*16;//如果是数字的话这样处理
}
else
{
a+=(str[0]-'a'+10)*16;//如果是字母的话这样处理
}
//处理第二个数字
if(str[1] >= '0' && str[1] <= '9')
{
a+=(str[1]-'0');
}
else
{
a+=(str[1]-'a'+10);
}
return a;//返回一个整数
}
string judge(string a)//寻找离答案最近的一个值
{
int minn = 9999999;
string t;//用来存答案
for(int i = 0; i < 16; i++)
{
//将可能的答案res[]中的值,与当前的值相减,找出差值最小的即可
if(abs(ex(a)-ex(res[i])) < minn)
{
minn = abs(ex(a)-ex(res[i]));
t = res1[i];//因为答案是一位,所以用res1
}
}
return t;
}
int main()
{
string str;
while(cin>>str)
{
string a,b,c;//两个两个分开
a = str.substr(1,2);
b = str.substr(3,2);
c = str.substr(5,2);
cout << "#"<return 0;
}