Similar RGB Color

easy math strings greedy

Problem

Given a hex string "#abcdef", return the closest similar color of the form "#XYZXYZ" (a 3-digit hex shorthand). Two colors are compared by sum of squared channel differences.

Inputcolor = "#09f166"
Output"#11ee66"
Each pair is rounded to the nearest multiple-of-17 value.

def similarRGB(color):
    def closest(pair):
        val = int(pair, 16)
        q = round(val / 17)
        return f"{q*17:02x}"
    return '#' + closest(color[1:3]) + closest(color[3:5]) + closest(color[5:7])
var similarRGB = function(color) {
    const closest = (pair) => {
        const v = parseInt(pair, 16);
        const q = Math.round(v / 17);
        return (q * 17).toString(16).padStart(2, '0');
    };
    return '#' + closest(color.slice(1,3)) + closest(color.slice(3,5)) + closest(color.slice(5,7));
};
class Solution {
    public String similarRGB(String color) {
        return "#" + closest(color.substring(1, 3)) + closest(color.substring(3, 5)) + closest(color.substring(5, 7));
    }
    private String closest(String pair) {
        int v = Integer.parseInt(pair, 16);
        int q = (int) Math.round(v / 17.0);
        return String.format("%02x", q * 17);
    }
}
class Solution {
    string closest(const string& pair) {
        int v = stoi(pair, nullptr, 16);
        int q = (int) round(v / 17.0);
        char buf[3]; snprintf(buf, sizeof(buf), "%02x", q * 17);
        return string(buf);
    }
public:
    string similarRGB(string color) {
        return "#" + closest(color.substr(1, 2)) + closest(color.substr(3, 2)) + closest(color.substr(5, 2));
    }
};
Time: O(1) Space: O(1)