要求:
rgb(255, 255, 255) # returns FFFFFF rgb(255, 255, 300) # returns FFFFFF rgb(0,0,0) # returns 000000 rgb(148, 0, 211) # returns 9400D3
解法一:
#include <iostream>
#include <string>
#include <sstream>
#include <cctype>
using namespace std;
class RGBToHex
{
public:
static std::string rgb(int r, int g, int b);
};
std::string RGBToHex::rgb(int r, int g, int b) {
stringstream s;
if (r > 255) r = 255;
if (r < 0) r = 0;
if (g > 255) g = 255;
if (g < 0) g = 0;
if (b > 255) b = 255;
if (b < 0) b = 0;
if (r < 16)
s << hex << 0 << r;
else
s << hex << r;
if (g < 16)
s << hex << 0 << g;
else
s << hex << g;
if (b < 16)
s << hex << 0 << b;
else
s << hex << b;
string s_r;
s >> s_r;
for (unsigned int i = 0; i < s_r.size(); i++)
if (s_r[i] >= 'a' && s_r[i] <= 'z')
s_r[i] = s_r[i] - 32;
return s_r;
}
优秀解法:
using namespace std;
class RGBToHex
{
public:
static std::string rgb(int r, int g, int b){
stringstream ss;
char c[16]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
if(r<0) r=0;
if(g<0) g=0;
if(b<0) b=0;
if(r>255) r=255;
if(g>255) g=255;
if(b>255) b=255;
ss<<c[(int)r/16]<<c[r%16]<<c[(int)g/16]<<c[g%16]<<c[(int)b/16]<<c[b%16];
return ss.str();
}
};
优秀解法二:
#include <algorithm>
#include <cstdio>
namespace RGBToHex
{
std::string rgb(int r, int g, int b)
{
char result[7];
std::sprintf(result, "%02X%02X%02X",
std::clamp(r, 0, 255),
std::clamp(g, 0, 255),
std::clamp(b, 0, 255));
return result;
}
}