In the following, every capital letter represents some hexadecimal digit from0tof.

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:

  • coloris a string of length7.
  • coloris a valid RGB color: fori > 0,color[i]is a hexadecimal digit from0tof
  • 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.

这个题比较简单,稍微有点恶心,对输入的string,从index 1开始,把每两个字符的子字符串转换为最接近的16进制”AA"形式的数,然后拼在一起就可以了。要注意的一点是,颜色字符串必须是7个字符,记得对于0一定要转化成00才可以

class Solution {
    public String similarRGB(String color) {
        StringBuilder res = new StringBuilder("#");
        for(int i = 1; i < color.length(); i += 2) {
            res.append(process(color.substring(i, i + 2)));
        }

        return res.toString();
    }

    public String process(String hex) {
        int[] nums = new int[] {0x0, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF};

        int num = Integer.parseInt(hex, 16);
        int res = nums[0];

        for(int i = 1; i < nums.length; i++) {
            if(Math.abs(num - nums[i]) < Math.abs(num - res)) {
                res = nums[i];
            }
        }

        if(res != 0x0)
            return Integer.toHexString(res);
        else
            return "00";
    }
}

results matching ""

    No results matching ""