800. 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"

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
  • 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.

Rust Solution

struct Solution;

use std::i32;

impl Solution {
    fn most_similar(x: i32) -> i32 {
        let mut min = i32::MAX;
        let mut res = 0;
        for i in 0..16 {
            if (x - i * 17).abs() < min {
                min = (x - i * 17).abs();
                res = i * 17;
            }
        }
        res
    }
    fn similar_rgb(color: String) -> String {
        let r = i32::from_str_radix(&color[1..3], 16).unwrap();
        let g = i32::from_str_radix(&color[3..5], 16).unwrap();
        let b = i32::from_str_radix(&color[5..7], 16).unwrap();
        format!(
            "#{:02x}{:02x}{:02x}",
            Self::most_similar(r),
            Self::most_similar(g),
            Self::most_similar(b)
        )
    }
}

#[test]
fn test() {
    let color = "#09f166".to_string();
    let res = "#11ee66".to_string();
    assert_eq!(Solution::similar_rgb(color), res);
}

Having problems with this solution? Click here to submit an issue on github.