#800
Easy Algorithms Similar rgb color
Math String Enumeration
67.9% acceptance
Mar 31, 2026
112
692
The red-green-blue color "#AABBCC" can be written as "#ABC" in shorthand.
For example, "#15c" is shorthand for the color "#1155cc".
The similarity between the two colors "#ABCDEF" and "#UVWXYZ" is -(AB - UV)2 - (CD - WX)2 - (EF - YZ)2.
Given a string color that follows the format "#ABCDEF", return a string represents the color that is most similar to the given color and has a shorthand (i.e., it can be represented as some "#XYZ").
Any answer which has the same highest similarity as the best answer will be accepted.
Solution
Rust
Time O(2^n)
Space O(n)
impl Solution {
pub fn similar_rgb(color: String) -> String {
let bytes = color.as_bytes();
let mut result = String::from("#");
for i in 0..3 {
let hi = Self::hex_val(bytes[1 + i * 2]);
let lo = Self::hex_val(bytes[2 + i * 2]);
let val = (hi << 4) | lo;
let best = ((val as f64 / 17.0).round() as u32).min(15) * 17;
result.push(char::from_digit(best / 16, 16).unwrap());
result.push(char::from_digit(best % 16, 16).unwrap());
}
result
}
fn hex_val(b: u8) -> u32 {
if b.is_ascii_digit() { (b - b'0') as u32 } else { (b - b'a' + 10) as u32 }
}
}