Find the closest hex color shorthand
In CSS, colors can be specified by a "hex triplet" - a three byte (six digit) hexadecimal number where each byte represents the red, green, or blue components of the color. For instance, #FF0000
is completely red, and is equivalent to rgb(255, 0, 0)
.
Colors can also be represented by the shorthand notation which uses three hexadecimal digits. The shorthand expands to the six digit form by duplicating each digit. For instance, #F00
becomes #FF0000
.
Since there are fewer digits in the hex shorthand, fewer colors can be represented.
The challenge
Write a program or function that takes a six digit hexadecimal color code and outputs the closest three-digit color code, where closeness is measured by adding together the difference between each component of the full color code and the corresponding component of the shorthand color code.
Your program or function must accept as input a six digit hexadecimal color code prepended with #
and output a three digit color code prepended with #
.
Examples
- #FF0000 → #F00
- #00FF00 → #0F0
- #D913C4 → #D1C
- #C0DD39 → #BD3