[lintcode] problem 1017 – similar rgb color

In the following, every capital letter represents some hexadecimal digit from 0 to f.

The red-green-blue color “#AABBCC” can be written as “#ABC” in shorthand. For example, “#15c” is shorthand for the color “#1155cc”.

Now, say the similarity between two colors “#ABCDEF” and “#UVWXYZ” is -(AB - UV)^2 - (CD - WX)^2 - (EF - YZ)^2.

Given the color “#ABCDEF”, return a 7 character color that is most similar to #ABCDEF, and has a shorthand (that is, it can be represented as some “#XYZ”)

Note

  • color is a string of length 7.
  • color is a valid RGB color: for i > 0, color[i] is a hexadecimal digit from 0 to f
  • Any answer which has the same (highest) similarity as the best answer will be accepted.
  • All inputs and outputs should use lowercase letters, and the output is 7 characters.

Example

No.1

Input: color = “#09f166”

Output: “#11ee66”

Explanation:
The similarity is -(0x09 - 0x11)^2 -(0xf1 - 0xee)^2 - (0x66 - 0x66)^2 = -64 -9 -0 = -73.
This is the highest among any shorthand color.

No.2

Input: color = “#010000”

Output: “#000000”

Explanation:
The similarity is -(0x01 - 0x10)^2 -(0x00 - 0x00)^2 - (0x00 - 0x00)^2 = -1 -0 -0 = -1.
This is the highest among any shorthand color.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public String (String color) {
StringBuilder sb = new StringBuilder("#");

for (int i = 1; i < color.length(); i += 2)
sb.append(helper(color.substring(i, i + 2)));

return sb.toString();
}

private String helper(String str) {
int num = Integer.parseInt(str, 16);
num = num / 17 + (num % 17 > 8 ? 1 : 0);
return String.format("%02x", num * 17);
}