In the following, every capital letter represents some hexadecimal digit from0
tof
.
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"
Example 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.
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
class Solution {
public String similarRGB(String color) {
String[] nums = {"00", "11", "22", "33", "44", "55", "66", "77", "88", "99", "aa", "bb", "cc", "dd", "ee", "ff"};
return "#" + findNearest(nums, color.substring(1, 3)) + findNearest(nums, color.substring(3, 5)) + findNearest(nums, color.substring(5, 7));
}
private String findNearest(String[] nums, String str){
int min = Integer.MAX_VALUE;
String ans = "";
for (String num : nums){
int a = Integer.parseInt(str, 16);
int b = Integer.parseInt(num, 16);
if (Math.abs(a - b) < min){
min = Math.abs(a - b);
ans = num;
}
}
return ans;
}
}