zoukankan      html  css  js  c++  java
  • 【python解题笔记20210318】CodeWars:RGB To Hex Conversion

    题目

    内容:输入RGB数字(有效范围0~255),将其转换成十六进制的结果

    链接:https://www.codewars.com/kata/513e08acc600c94f01000001/train/python

    截图:

        

    解题

    思路: 

    1、将范围外的输入,转成0或者255

    2、将十进制整数rgb转换十六进制+转成字符串+去掉前缀0x+将小写转换成大写

    3、如果得到的结果只有1位数,则前面补0

    结果:

       

    源码:

    def rgb(r, g, b):
        """
        输入RGB数字(有效范围0~255),将其转换成十六进制的结果
        :param r: red参数
        :param g: green参数
        :param b: blue参数
        :return: RGB拼接后的十六进制字符串
        """
        #将范围外的输入,转成0或者255
        if r<0:
            r=0
            pass
        elif r>255:
            r=255
            pass
        if g<0:
            g=0
            pass
        elif g>255:
            g=255
            pass
        if b<0:
            b=0
            pass
        elif b > 255:
            b = 255
            pass
        #将十进制整数rgb转换十六进制+转成字符串+去掉前缀0x+将小写转换成大写
        r = str(hex(r))[2:].upper()
        g = str(hex(g))[2:].upper()
        b = str(hex(b))[2:].upper()
        #如果得到的结果只有1位数,则前面补0
        if len(r)==1:
            r='0'+r
            pass
        if len(g)==1:
            g='0'+g
            pass
        if len(b)==1:
            b='0'+b
            pass
        #返回拼接的RGB十六进制字符串
        return r+g+b

    知识点

    1、hex()函数将十进制转成十六进制。

    2、str()函数将数字转成字符串。

    3、str[num1:num2]可以做字符串截取,去掉前面的num1位,以及后面的num2位。

    4、upper()函数将小写转成大写字母,如果传入数字也不会报错。

    参考资料:

    https://blog.csdn.net/qq_34783484/article/details/97654167

    https://jingyan.baidu.com/article/8cdccae9bded64705413cdd8.html

  • 相关阅读:
    IOS-自定义返回按钮,保留系统滑动返回
    IOS-static cell 与 dynamic cell 混合使用
    IOS-快速集成检查更新
    IOS-如何优雅地拦截按钮事件(判断是否需要登录)
    IOS-更优雅地使用Static Cell
    Xcode8出现问题总结
    IOS-工程师Mac上的必备软件
    Minimum Sum of Array(map迭代器)
    C++ STL map
    Friends and Cookies(思维)
  • 原文地址:https://www.cnblogs.com/chooperman/p/14556967.html
Copyright © 2011-2022 走看看