물음표 살인마의 개발블로그

알고리즘 문제/CodeWar

RGB to Hex Conversion

BEstyle 2022. 10. 6. 13:10

DESCRIPTION:

The rgb function is incomplete. Complete it so that passing in RGB decimal values will result in a hexadecimal representation being returned. Valid decimal values for RGB are 0 - 255. Any values that fall out of that range must be rounded to the closest valid value.

Note: Your answer should always be 6 characters long, the shorthand with 3 will not work here.

The following are examples of expected output values:

rgb(255, 255, 255) # returns FFFFFF
rgb(255, 255, 300) # returns FFFFFF
rgb(0,0,0) # returns 000000
rgb(148, 0, 211) # returns 9400D3

ef rgb(r, g, b):
    ans=""
    if r<0:
        r=0
    elif r>255:
        r=255
    if g<0:
        g=0
    elif g>255:
        g=255
    if b<0:
        b=0
    elif b>255:
        b=255
    adict={10:'A',11:'B',12:'C',13:'D',14:'E',15:'F'}
    alist=[r,g,b]
    head=0
    for i in alist:
        while i>=16:
            head+=1
            i-=16
        if head>=10:
            ans+=adict[head]
        else:
            ans+=str(head)
        if i>=10:
            ans+=adict[i]
        else:
            ans+=str(i)
        head=0
    return ans

'알고리즘 문제 > CodeWar' 카테고리의 다른 글

Valid Braces  (0) 2022.10.06
Valid Parentheses  (0) 2022.10.06
Human Readable Time  (0) 2022.10.05
Moving Zeros To The End  (1) 2022.10.05
Printer Errors  (1) 2022.10.05