返回介绍

solution / 0800-0899 / 0800.Similar RGB Color / README_EN

发布于 2024-06-17 01:03:34 字数 3168 浏览 0 评论 0 收藏 0

800. Similar RGB Color

中文文档

Description

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.

 

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.

Example 2:

Input: color = "#4e3fe1"
Output: "#5544dd"

 

Constraints:

  • color.length == 7
  • color[0] == '#'
  • color[i] is either digit or character in the range ['a', 'f'] for i > 0.

Solutions

Solution 1

class Solution:
  def similarRGB(self, color: str) -> str:
    def f(x):
      y, z = divmod(int(x, 16), 17)
      if z > 8:
        y += 1
      return '{:02x}'.format(17 * y)

    a, b, c = color[1:3], color[3:5], color[5:7]
    return f'#{f(a)}{f(b)}{f(c)}'
class Solution {
  public String similarRGB(String color) {
    String a = color.substring(1, 3), b = color.substring(3, 5), c = color.substring(5, 7);
    return "#" + f(a) + f(b) + f(c);
  }

  private String f(String x) {
    int q = Integer.parseInt(x, 16);
    q = q / 17 + (q % 17 > 8 ? 1 : 0);
    return String.format("%02x", 17 * q);
  }
}
func similarRGB(color string) string {
  f := func(x string) string {
    q, _ := strconv.ParseInt(x, 16, 64)
    if q%17 > 8 {
      q = q/17 + 1
    } else {
      q = q / 17
    }
    return fmt.Sprintf("%02x", 17*q)

  }
  a, b, c := color[1:3], color[3:5], color[5:7]
  return "#" + f(a) + f(b) + f(c)
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文