Categories:

Tags:



Problem

The red-green-blue color "#AABBCC" can be written as "#ABC" in shorthand.

  • For example, "#15c" is shorthand for the color "#1155cc".

The similarity between the two colors "#ABCDEF" and "#UVWXYZ" is -(AB - UV)2 - (CD - WX)2 - (EF - YZ)2</coe>.

Given a string color that follows the format "#ABCDEF", return a string represents the color that is most similar to the given color and has a shorthand (i.e., it can be represented as some "#XYZ").

Any answer which has the same highest similarity as the best answer will be accepted.

Constraints

  • color.length == 7
  • color[0] == '#'
  • color[i] is either digit or character in the range ['a', 'f'] for i > 0.

Solution

The problem Similar RGB Color can be solved by dividing each RGB value by 17 and rounding it. Let 0xAB one of the RGB value. Since all 0xXX is a multiple of 0x11, 0xAB / 0x11 = n * 0x11 + α where n is the quotient and α is the remainder. If α <= 8, then the nearest 0xXX to 0xAB is 0x11 * n. Otherwise, the nearest 0xXX to 0xAB is 0x11 * (n + 1). By rounding the division result, we can automatically calculates the nearest 0xXX value.

Implementation

static const int fast_io = []()
{
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    return 0;
}();

class Solution
{
  public:
    string similarRGB(string color)
    {
        char ret[8] = "#";
        for (int i = 0; i < 3; i++)
        {
            int num = stoi(color.substr(1 + i * 2, 2), NULL, 16);
            num = round(num / 17.0) * 17;
            sprintf(ret + 1 + i * 2, "%02x", num);
        }

        return ret;
    }
};